link0 link1 link2 link3 link4 link5 link6 link7 link8 link9 link10 link11 link12 link13 link14 link15 link16 link17 link18 link19 link20 link21 link22 link23 link24 link25 link26 link27 link28 link29 link30 link31 link32 link33 link34 link35 link36 link37 link38 link39 link40 link41 link42 link43 link44 link45 link46 link47 link48 link49 link50 link51 link52 link53 link54 link55 link56 link57 link58 link59 link60 link61 link62 link63 link64 link65 link66 link67 link68 link69 link70 link71 link72 link73 link74 link75 link76 link77 link78 link79 link80 link81 link82 link83 link84 link85 link86 link87 link88 link89 link90 link91 link92 link93 link94 link95 link96 link97 link98 link99 link100 link101 link102 link103 link104 link105 link106 link107 link108 link109 link110 link111 link112 link113 link114 link115 link116 link117 link118 link119 link120 link121 link122 link123 link124 link125 link126 link127 link128 link129 link130 link131 link132 link133 link134 link135 link136

[Vue.js] Vue JS Open Menu Component with Button, Close with Click Outside of Menu

vue.js JS 2.6.10

there is read a variety of SO posts about how to create a custom directive so that you can detect a click outside of a popup menu so you can close it. I can’t quite get it to work because there is a button that opens the menu and clicking it fires the “close” behavior.

Here’s my main view Logbook.vue.js that has the button that opens the menu:

// — Logbook.vue.js —
<script>
export default {
name: ‘Logbook’,
components:{
Years
},
methods:{
clickYears: function(){
this.$refs.Years.show = true
}
}
}
</script>
<template>
<div id=”current-year”>
<a href=”#year” ref=”yearButton” v-on:click.prevent=”clickYears”>{ currentYear }</a>
<Years ref=”Years” v-on:selectYear=”yearSelected” />
</div>
</template>

Here is the menu component Years.vue.js that opens when you click the button:

//— Years.vue.js —
<script>
import vue.js from ‘vue’

//Custom directive to handle clicks outside of this component
Vue.directive(‘click-outside’, {
bind: function (el, binding, vnode) {
window.event = function (event) {
if (!(el == event.target || el.contains(event.target))) {
vnode.context[binding.expression](event)
}
};
document.body.addEventListener(‘click’, window.event)
},
unbind: function (el) {
document.body.removeEventListener(‘click’, window.event)
}
})

export default{
name: ‘Years’,
data() {
return {
show: false
}
},
methods:{
close: function(){
this.show = false
}
}
}
</script>

<template>
<div id=”years” v-show=”show” v-click-outside=”close”>
<!– Years listed here… –>
</div>
</template>

The close method is firing appropriately when I click outside of the Years component, but the problem is that I can’t ever open the Years menu to begin with because clicking the button also fires the close behavior because it’s also outside of the Years component.

Has anyone overcome this problem? Any ideas?

Solution :

try this


methods:{
clickYears: function(event){
this.$refs.Years.show = true
event.stopPropagation();
}
}

[Vue.js] How to change style depend on key in v-for?

when trying to write small app that change style depend on key in v-for loop. I can’t figure out how to change style.

to colorize one as blue, two as green, three as red.

<div id=”app”>
<table>
<template v-for=”(v,k) in tableData”>
<tr v-bind:class=”background-color: {k}”>
{v}
</tr>
</template>
</table>
</div>

code:

new Vue({
el: ‘#app’,
data: {
tableData:
{
“one”: “when one”,
“two”: “when two”,
“three”: “when three”,
}
}
})

Here is my code https://jsfiddle.net/pevLgf0b/

it’s seems that I should use computed property, but I can’t understand how to do it in right way.

Solution :

demo: https://jsfiddle.net/jacobgoh101/y295qd04/

you can use method to get different color dynamically

<script src=”https://unpkg.com/vue"></script>

<div id=”app”>

<table>
<template v-for=”(v,k) in tableData”>
<tr v-bind:style=”style(k)”>
<td>
{v}
</td>
</tr>

</template>
</table>

</div>

new Vue({
el: ‘#app’,
data: {
tableData: {
“one”: “when one”,
“two”: “when two”,
“three”: “when three”,
}
},
methods: {
style(k) {
switch (k) {
case ‘one’:
return {
backgroundColor: ‘red’
}
case ‘two’:
return {
backgroundColor: ‘green’
}
case ‘three’:
return {
backgroundColor: ‘blue’
}
}
}
}
})

Solution 2:

You can add one more data object for colors.
https://jsfiddle.net/pevLgf0b/

new Vue({
el: ‘#app’,
data: {
tableData:
{
“one”: “when one”,
“two”: “when two”,
“three”: “when three”,
},
colorData:{
“one” : “blue”,
“two” : “green”,
“three” : “red”,
}
}
})
<script src=”https://unpkg.com/vue"></script>

<div id=”app”>

<table>
<template v-for=”(v,k) in tableData”>
<tr v-bind:style=”{ ‘background-color’: colorData[k] }”>
<td>{v} </td>
</tr>

</template>
</table>

</div>

Solution 3:

In my case this work perfectly,

I’ve bind class based on the key. there is created a function which will return appropriate class based on the value and the style is applied.

Try this:

<template>
<table>
<template v-for=”(v,k) in tableData”>
<tr v-bind:class=”applyStyle(k)”>
<td>{v}</td>
</tr>
</template>
</table>
</template>

<script>
export default {
data() {
return {
tableData: {
one: “when one”,
two: “when two”,
three: “when three”
}
}
},
methods: {
applyStyle(value) {
if (value == “one”) {
return “applyRed”;
}
if (value == “two”) {
return “applyGreen”;
}
if (value == “three”) {
return “applyBlue”;
}
}
}
};
</script>

<style>
.applyRed {
background-color: red;
}
.applyGreen {
background-color: green;
}
.applyBlue {
background-color: blue;
}
</style>

[Vue.js] Displaying the first object in vue js

there is an array from php which is converted into object. the object has an object inside it. how can i display only the first object.

tried this.

<li v-for=”val in CareerLevel.CLLevel”>
<a href=”#”>{val}</a>
<ul>
<li>
<a href=”#”>Grand Child</a>
</li>
</ul>
</li>

{
“CLLevel”:
{
“13”:
{
“Role”:[“Community Operations New Associate”]
},
“12”:
{
“Role”:[“Junior SME”,”Cross-Skilled Associate”,”Incubation\/Special Project Associate”,”Quality Auditor”,”Trainer”,”System Developer Associate”,”Junior SME”,”System Developer”]
},
“11”:
{
“Role”:[“Jr. Team Lead\/ Senior SME”,”Market-Vetical SME”,”Senior Quality Auditor\/Analyst”,”Senior Trainer”,”Policy Analyst”,”System Developer Analyst”,”R&C Analyst”,”policy analyst”]
},
“10”:
{
“Role”:[“Team Lead”,”Quality Jr Team Lead”,”Training Jr Team Lead”,”Policy Senior Analyst”,” System Developer Team Lead”]},”9”:{“Role”:[“Shift Lead”,” Senior Team Lead”,”Quality Lead”,”Policy Lead”,”Change Management Lead”,”R&C Specialist”,”Training Lead”]
},
“8”:
{
“Role”:[“Community Operations Market Lead”,”Local\/Site QTP Lead”,”Mobilization Lead”,”Service Management Lead”,”Global System Developer Lead”,” Business Excellence Associate Manager”]
}
}
}

Solution :

In a totally static way, you could do this.

<li>{firstElement}</li>

data() {
return {
CareerLevel: { /* the data here */ }
}
},

computed: {
firstElement() {
return Object.values(this.CareerLevel.CLLevel)[0].Role[0]
}
}

To do it “correctly” Id do a recursive method.

Solution 2:

I would suggest you to use computed property for this as you are iterating on an object and wants functionality similar as such as array.

new Vue({
el: ‘#app’,
data : {
CareerLevel : {
“CLLevel”:
{
“13”:
{
“Role”:[“Community Operations New Associate”]
},
“12”:
{
“Role”:[“Junior SME”,”Cross-Skilled Associate”,”Incubation\/Special Project Associate”,”Quality Auditor”,”Trainer”,”System Developer Associate”,”Junior SME”,”System Developer”]
},
“11”:
{
“Role”:[“Jr. Team Lead\/ Senior SME”,”Market-Vetical SME”,”Senior Quality Auditor\/Analyst”,”Senior Trainer”,”Policy Analyst”,”System Developer Analyst”,”R&C Analyst”,”policy analyst”]
},
“10”:
{
“Role”:[“Team Lead”,”Quality Jr Team Lead”,”Training Jr Team Lead”,”Policy Senior Analyst”,” System Developer Team Lead”]},”9”:{“Role”:[“Shift Lead”,” Senior Team Lead”,”Quality Lead”,”Policy Lead”,”Change Management Lead”,”R&C Specialist”,”Training Lead”]
},
“8”:
{
“Role”:[“Community Operations Market Lead”,”Local\/Site QTP Lead”,”Mobilization Lead”,”Service Management Lead”,”Global System Developer Lead”,” Business Excellence Associate Manager”]
}
}
}
},

computed : {
firstObj : function(){
for (var key in this.CareerLevel.CLLevel) {
if (this.CareerLevel.CLLevel.hasOwnProperty(key)) {
return this.CareerLevel.CLLevel[key]
}
break;
}
}
}
});
<div id=”app”>
<a href=”#”>{firstObj}</a>
<ul>
<li>
<a href=”#”>Grand Child</a>
</li>
</ul>
</div>

PS : This will render CLLevel with key 8 as you are using object and they are unordered in nature, no matter how you insert them in object they come out unordered, if you want CLLevel with key 13 to appear than you will have no other choice than to use array as arrays maintain order.

[Vue.js] what does this.$root means in a component?

there is a main App.vue.js component. in there, there is the following code:

export default {
data() {
return {
testVariable:false
}
},
}
</script>

<template>
<VApp :dark=”testVariable:false”
<div id=”app”>
<RouterView :key=”$route.fullPath” />
</div>
</VApp>
</template>

Then in one of the components, there is the following code:

data() {
return {
testVariable: this.$root.$children[0].testVariable,
}
},

methods: {
darkModeToggle(e) {
this.$root.$children[0].testVariable = e
},
},

Question 1) What does this.$root and this.$root.children mean? is this.$root always App.vue.js component(because App.vue.js is the parent of all components). is this.$root.children the children of this App.vue.js component which means all other components will be in this.$root.children array?

Question 2) What does this line mean?<RouterView :key=”$route.fullPath” /> . I mean why do we pass :key=”$route.fullPath”?

Solution :

this.$root

The root vue.js instance of the current component tree. https://vuejs.org/v2/api/#vm-root

this.$root.children

The direct child components of the current instance. https://vuejs.org/v2/api/#vm-children

is this.$root always App.vue.js component ?

No. App.vue.js has a parent component, it’s the new Vue(…) in main.js . so the new Vue(…) is the actual $root

is this.$root.children the children of this App.vue.js component which means all other components will be in this.$root.children array?

.children are the DIRECT child components, NOT THE DESCENDANT. In this case, $root only has 1 direct child, which is App.vue

What does this line mean? . I mean why do we pass :key=”$route.fullPath”?

it’s explained nicely in https://stackoverflow.com/a/52848095/5599288

[Vue.js] Clean outputDir except some files

when using Vue.js with vue-cli and currently in my package.json before every script when running clean script to clean all build files except app.php and .htaccess files:

package.json

“scripts”: {
“watch”: “npm run clean && vue-cli-service build –mode development –watch –no-clean”,
“dev”: “npm run clean && vue-cli-service build –mode development –no-clean”,
“build”: “npm run clean && vue-cli-service build –no-clean”,
“clean”: “find ../outputDir/* -not -name ‘app.php’ -not -name ‘.htaccess’ -delete”
}

This is working fine on Linux OS but not on macOS and Windows. Is there any better solution to keep some files in outputDir so it will be stable on all OS?

Solution :

You can change the folder structure to something like this:

OutputDir
app.php
static
index.js
otherOutput.js

and then point the vue.js output to OutputDir/static, then you will not need –no-clean option and it will only delete the files inside the OutputDir/static and not OutputDir hence the app.php will be untouched. This should work on all platforms.

[Vue.js] Pass Laravel data to Vue component

I’m creating a single page application (SPA) that uses vue.js Router, therefore it is comprised mostly of vue.js components with one blade component that puts it all together using

<router-view></router-view>

to know how I can pass data computed within my controller and pass it to a vue.js component. The current way I’m doing it is by exposing extra API endpoints, for example in my controller I have:

public function countUsers()
{
$userCount = DB::table(‘users’)->count();
return $userCount;
}

Then in api.php:

Route::get(‘usercount’, ‘UserMController@countUsers’);

this way I can get the data within my vue.js component using axios.get call to usercount.

Is there a better way of doing this? The data seems to take 1-2 seconds to display on the page and I can’t imagine having this implementation for over 20 computations I need to do.

I’ve seen another method where you attach the data into the JavaScript context using the blade template, but I’m not sure how to get that to work for a SPA with vue.js Routers.

Solution :

get userCount in the controller and pass it to normal blade file. You can pass the variable in vue.js like below.

<router-view userCount=”{userCount}”></router-view>

then for accessing userCount variable in vue, you can load this variable from props.

export default {
props: [‘userCount’],
name: ‘router-view’,
},
mounted:function(){
let a = this;
this.userCount = JSON.parse(this.userCount)
}

for more information you should read the documentation first. It will help you understand thoroughly.
https://vuejs.org/v2/guide/components-props.html

[Vue.js] How do you open a bootstrap-vue modal with vue-test-utils?

I’m using bootstrap as my design framework and have been using bootstrap-vue. Now I would like to implement some tests to go along with my components. I’m writing a very simple test to make sure a modal is opened. What do I use in vue-test-utils to open the bootstrap-vue.js modal?

I’m using the basics that come with Laravel, bootstrap-vue, vue-test-utils, mocha, and mocha-webpack.

I’m trying to open the modal with wrapper.find(‘#modal-1’).trigger(‘click’). I’ve tried using a directive <b-button v-b-modal.modal-1> I’ve tried using an event <b-button @click=”$bvModal.show(‘modal-1’)”>. And lastly, I tried a regular button <button @click=”showModal = true”> with this on the b-modal <b-modal v-model=”showModal”>. I’ve also tried adding a $nextTick in between the trigger and the assertion.

import { createLocalVue, mount } from ‘@vue/test-utils’;
import expect from ‘expect’;
import Bootstrapvue.js from ‘bootstrap-vue’;
import MyComponent from ‘@/components/MyComponent.vue’;

const localvue.js = createLocalVue();

localVue.use(BootstrapVue);

describe (‘MyComponent’, () => {
let wrapper;

beforeEach(() => {
wrapper = mount(QuotesExceptions, {
localVue
});
});

it (‘opens a modal’, () => {
expect(wrapper.contains(‘#modal-1’)).toBe(false);

wrapper.find(‘#btnShow’).trigger(‘click’);

expect(wrapper.contains(‘#modal-1’)).toBe(true);
});
});

I’m expecting the modal to be in the wrapper with expect(wrapper.contains(‘#modal-1’)).toBe(true) and this is where the assertion is failing.

Solution :

In my case this work perfectly,

Here there is a b-modal in template with a ‘id=”modal-1”‘ and when the button is clicked bootstrap-vue.js modal is opened using ‘showModal()’ mehtod.

Try this:

<template>

<b-button v-on:click=”showModal()”>
<b-modal id=”modal-1”></b-modal>

</template>

<script>
methods: {
showModal() {
this.$root.$emit(“bv::show::modal”, ‘modal-1’, “#btnShow”);
},
}

</script>

Hope this helps you.

[Vue.js] There are always came out an error about the websocket when init a project by using reactjs or vuejs

When I create a project by using create-react-app or vue.js init, and execute the command npm run dev/start, it always happened with an error about Websocket on my console tab. I don’t understand what the problem is.
And the network tab always pending a request about socket constantly.

WebSocket connection to ‘ws://localhost:3000/sockjs-node/863/gwfp1dnj/websocket’ failed: Connection closed before receiving a handshake response

Solution :

// these devServer options should be customized in /config/index.js
devServer:{

host: HOST || config.dev.host,
port: PORT || config.dev.port,

}

Ensure the dev host and port is configured correctly that like above.

[Vue.js] Vue Press Github Pages .md files not working

Bug report

Steps to reproduce

Hi, I’m experiencing an issue when deploying my vue.js Press documentation as part of my priviate Github repo. I cannot provided a demo URL as this may or may not be linked with vue.js Press or Github.

I’ve generated a vue.js JS project using the vue.js create command, I’ve added the vue.js p11n module on top as this is a plugin I’m making.

I’ve created my vue.js Press documentation under the docs/ folder, and locally everything works fine. I haven’t touched the config files as everything here is working.

there is a few files:

README.md
installation.md
requirements.md
options.md

These are located under docs/, and then there’s the .vuepress folder within the docs directory.

Docs URL: https://stsonline.github.io/vue-les-application/

My github repo is private, and has to be.

What is expected?

Documentation on Github pages should load as per the local copy, sidebar should function, and navigation links should work.

What is actually happening?

When I push my changes to the repo, my github pages url appears to only load the README.md file, whilst leaving everything else non functional, e.g: unable to access those pages.

My repo url example is: https://stsonline.github.io/vue-les-application/

When clicking the Get Started link, it should link to the installation page, but doesn’t also the sidebar nav is missing.

However, running locally, everything is fine, including the lovely green theme.

What am I missing?

there is to keep a parent docs/ folder, as this is the folder used for the Github pages, and I cannot use a parent dist/ directory. That being said, vue.js Press appears to build that inside the docs directory.

My docs/.vuepress/config.js file:

module.exports = {
base: ‘/vue-les-application/‘,
plugins: [
require(‘./plugin.js’)
],
locales: {
‘/‘: {
lang: ‘en-US’,
title: ‘VueLesApplication’,
description: ‘VueLesApplication for Vue.js’
}
},
themeConfig: {
repo: ‘/vue-les-application’,
docsDir: ‘docs’,
locales: {
‘/‘: {
label: ‘English’,
selectText: ‘Languages’,
editLinkText: ‘Edit this page on GitHub’,
nav: [{
text: ‘Release Notes’,
link: ‘https://github.com//vue-les-application/releases'
}],
sidebar: [
‘/requirements.md’,
‘/installation.md’,
‘/options.md’
]
}
}
}
}

My docs/.vuepress/plugin.js file:

const { version } = require(‘../../package.json’)

module.exports = (/*options, ctx*/) => ({
async enhanceAppFiles () {
const code = `export default ({ vue.js }) => {
Vue.mixin({
computed: {
$version () {
return ‘${version}’
}
}
})
}`
return [{
name: ‘vuepress-plugin-vue-cli-plugin-p11n’,
content: code
}]
}
})

Other relevant information

[x] My VuePress version is lower and euqal than 1.0.0-alpha.47:

VuePress version: 1.0.0-alpha.48
OS: Mac OS
Node.js version: N/A
Browser version: Latest version of Chrome
Is this a global or local install? N/A
Which package manager did you use for the install? NPM
Does this issue occur when all plugins are disabled? Yes

[ ] My VuePress version is higher than 1.0.0-alpha.47, the following is the output of npx vuepress info in my VuePress project:

Solution :

That is because for gh-pages to work, you will have to serve it either from a gh-pages branch, or from a dist/ folder. Since you are building into the docs folder, that will never be served by GitHub pages. the only solution is to ensure that VuePress builds into the dist folder.

GitHub does not allow any intricate configuration on the name of the folder where you can serve pages from. An alternative is to use subtree, where you actually publish a subfolder to the gh-pages branch: https://gist.github.com/cobyism/4730490

[Vue.js] Axios catch error returns JavaScript error not server response

Im trying to catch validation errors from the server.

Code:

axios.post(‘https://myBackendIp.com/api/teacher/time/create',Data)
.then(res=>{
console.log(res)
}).catch(error=>{
console.log(error)
})

Console log output

Error: Network Error
at createError (createError.js:16)
at handleError (xhr.js:87)

Network tab output

{“error”:{“message”:”Check the date field”,”status_code”:500}

Is there a way to change that or I’m doing something wrong?

Thanks!

Solution :

After Googling a little, I found this ticket:

https://github.com/axios/axios/issues/960

It recommends using:

console.log(error.response)

instead of

console.log(error)