link1918 link1919 link1920 link1921 link1922 link1923 link1924 link1925 link1926 link1927 link1928 link1929 link1930 link1931 link1932 link1933 link1934 link1935 link1936 link1937 link1938 link1939 link1940 link1941 link1942 link1943 link1944 link1945 link1946 link1947 link1948 link1949 link1950 link1951 link1952 link1953 link1954 link1955 link1956 link1957 link1958 link1959 link1960 link1961 link1962 link1963 link1964 link1965 link1966 link1967 link1968 link1969 link1970 link1971 link1972 link1973 link1974 link1975 link1976 link1977 link1978 link1979 link1980 link1981 link1982 link1983 link1984 link1985 link1986 link1987 link1988 link1989 link1990 link1991 link1992 link1993 link1994 link1995 link1996 link1997 link1998 link1999 link2000 link2001 link2002 link2003 link2004 link2005 link2006 link2007 link2008 link2009 link2010 link2011 link2012 link2013 link2014 link2015 link2016 link2017 link2018 link2019 link2020 link2021 link2022 link2023 link2024 link2025 link2026 link2027 link2028 link2029 link2030 link2031 link2032 link2033 link2034 link2035 link2036 link2037 link2038 link2039 link2040 link2041 link2042 link2043 link2044 link2045 link2046 link2047 link2048 link2049 link2050 link2051 link2052 link2053 link2054

[Vue.js] My html code can't reach my vue component

This is my second day with vue. I was already using webpack and vue-cli, but I would like to understand how to make everything working within one file. I developed a code which works well, but I would like to refactor the code to have a component which I could later use to generate screen full of color changing tiles.

I tried Vue.component(‘name’, {}), but with no result, because in the console I’m seeing [vue.js warn]: The “data” option should be a function that returns a per-instance value in component definitions. and [vue.js warn]: Unknown custom element: <brick> - did you register the component correctly? For recursive components, make sure to provide the “name” option.

This code works well:

<html>
<head>
<title>v pavle</title>
<script type=”text/javascript” src=”https://vuejs.org/js/vue.js"></script>
</head>
<body>
<div id=”app”></div>
<script type=”text/javascript”>
var vm = new Vue({
el: “#app”,
template:
‘<div v-bind:style=”styleobj” v-on:mouseover=”changebgcolor” v-on:mouseout=”changebgcolor”></div>’,
data: {
styleobj: {
width: “100px”,
height: “100px”,
backgroundColor: “white”
}
},
methods: {
changebgcolor: function() {
this.styleobj.backgroundColor = Math.floor(
Math.random() * 16777215
).toString(16);
}
}
});
</script>
</body>
</html>

And that code gives everything, but not what to see :(

<html>
<head>
<title>v pavle</title>
<script type=”text/javascript” src=”https://vuejs.org/js/vue.js"></script>
</head>
<body>
<div id=”app”>
<brick></brick>
</div>
<script type=”text/javascript”>
var vm = new Vue({
el: “#app”
});

var brick = Vue.component(“brick”, {
template:
‘<div v-bind:style=”styleobj” v-on:mouseover=”changebgcolor” v-on:mouseout=”changebgcolor”></div>’,
data: {
styleobj: {
width: “100px”,
height: “100px”,
backgroundColor: “white”
}
},
methods: {
changebgcolor: function() {
this.styleobj.backgroundColor = Math.floor(
Math.random() * 16777215
).toString(16);
}
}
});
</script>
</body>
</html>

It may seem easy for you, but after 7h spent, there is nothing more for me, but just ask you on SO

Solution :

Okay I will answer the 2 questions. First and about data, it has to be a function. So you have to write it like that:

data() {
return {
styleobj: {
width: “100px”,
height: “100px”,
backgroundColor: “white”
}
}
}

After that, the forgot to reference the component in the vue.js instance. Try that:

var vm = new Vue({
el: “#app”,
components: {
brick: brick
}
})

Hope it will work.

Solution 2:

Data must be a function like data: function(){ return obj }
Register the component using components: {yourcomponent}
You needed to use # in front of the color.

<html>
<head>
<title>v pavle</title>
<script type=”text/javascript” src=”https://vuejs.org/js/vue.js"></script>
</head>
<body>
<div id=”app”>
Hello App!
<brick>Hello Brick</brick>
</div>
<script type=”text/javascript”>
var brick = Vue.component(“brick”, {
template:
‘<div :style=”styl” @click=”changebgcolor” @mouseover=”changebgcolor” @mouseout=”changebgcolor”><slot></slot></div>’,
data: function(){
return {
styl: {
width: “100px”,
height: “100px”,
backgroundColor: “#b6d8a1”,
color: “blue”
}
};
},
methods: {
changebgcolor: function() {
console.log(‘changebgcolor!’);
this.styl.backgroundColor = “#”+ Math.floor(
Math.random() * 16777215
).toString(16);
}
}
});
var vm = new Vue({
el: “#app”,
components:{brick:brick}
});

</script>
</body>
</html>

Solution 3:

When using Vue.component, you need to make sure that you have registered all components once you start rendering the app. At the moment, you first render the main app and then register the component, so swap those around

var brick = Vue.component(“brick”, {
template:
‘<div v-bind:style=”styleobj” v-on:mouseover=”changebgcolor” v-on:mouseout=”changebgcolor”></div>’,
data: {
styleobj: {
width: “100px”,
height: “100px”,
backgroundColor: “white”
}
},
methods: {
changebgcolor: function() {
this.styleobj.backgroundColor = Math.floor(
Math.random() * 16777215
).toString(16);
}
}
});
var vm = new Vue({
el: “#app”
});

Solution 4:

The data property on the component should be a function that returns an object. Why? Because otherwise all instances of the component share the same data, meaning all tiles on the app would have the same color.

data() {
return {
styleobj: {
width: “100px”,
height: “100px”,
backgroundColor: “white”
}
}
},

You should first register the component before you fire up the vue.js instance, just reorder the code and it works!

[Vue.js] adding an item to the array causes Error in nextTick RangeError

when learning vue.js and when trying to create a dynamic component to build navigation with children.

there is tried to create a new object with Object.assign and new array with Array, but always the same result.

here is part of my app related to this problem:

https://jsfiddle.net/mL48st20/

problem occurs in
CmsMenuItem.createChild() (on line 155)

createChild: function () {

// force expand list
this.isExpanded = true;
console.log(“Item add-child”);

--> this.data.childrens.push($BLANK_ITEM);
},

Everything works just fine if I add a child to the existing item (loaded in vue.js constructor) The problem occurs only when I try to add a child to a newly created item.

It pushes the new object to the item children array and also to its children array and so on.. infinite times, which explains the error.

Do you guys have any idea, how to solve this?

Thanks in advance for any bits of advice.

Solution :

You’re setting the same $BLANK_ITEM instance as a child of different items. You need to create new item instances each time.

Instead of:

var $BLANK_ITEM = {
name: $texts.newItem,
url: ‘’,
languages: [],
siteId: ‘’,
icon: ‘’,
target: ‘_self’,
title: ‘’,
childrens: []
};

you should have a function which creates a new item instance:

function createBlankItem() {
return {
name: $texts.newItem,
url: ‘’,
languages: [],
siteId: ‘’,
icon: ‘’,
target: ‘_self’,
title: ‘’,
childrens: []
};
}

then replace $BLANK_ITEM throughout the code with createBlankItem(), e.g.:

methods: {
addItem: function () {
var item = createBlankItem();
this.$emit(‘add-item’, item);
this.data.push(item);
}
}

You also have some other errors related to the Sortable plugin, but I’m not sure what’s going on there.

[Vue.js] Why still adding even with validation form?

When I click the button on my modal with an empty field on my input its give me an undefined value on my console. And when I put a value on my input and click the button it is adding to my database. The problem is even the empty field or the undefined value are also adding to my database and the sweetalert is not working. to prevent the empty field adding to my database and prevent the undefined. Can somebody help me?

//start of method
checkForm: function(e) {
if (this.category_description) {
return true;
}

this.errors = [];

if (!this.category_description) {
this.errors.push(‘Category required.’);
}
e.preventDefault();
},

addCategory : function() {
axios({
method : “POST”,
url : this.urlRoot + “category/add_category.php”,
data : {
description : this.category_description
}
}).then(function (response){
vm.checkForm(); //for FORM validation
vm.retrieveCategory();
console.log(response);
swal(“Congrats!”, “ New category added!”, “success”);
vm.clearData();
}).catch(error => {
console.log(error.response);
});
},
//end of method

<form id=”vue-app” @submit=”checkForm”>
<div class=”modal” id=”myModal” > <!– start add modal –>
<div class=”modal-dialog”>
<div class=”modal-content “ style=”height:auto”>

<!– Modal Header –>
<div class=”modal-header”>
<h4 class=”modal-title”> Add Category </h4>
<button @click=”clearData” type=”button” class=”close” data-dismiss=”modal”><i class=”fas fa-times”></i></button>
</div>

<!– Modal body –>
<div class=”modal-body”>
<div class=”form-group”>
<div class=”col-lg-12”>
<input type=”text” class=”form-control” id=”category_description” name=”category_description” v-model=”category_description” placeholder=”Enter Description”>
<p v-if=”errors.length”>
<span v-for=”error in errors”> { error } </span>
</p>
</div>
</div>
</div>

<!– Modal footer –>
<div class=”modal-footer”>
<button type=”submit”@click=”category_description !== undefined ? addCategory : ‘’” class=”btn btn-primary”> Add Category </button>
</div>
</div>
</div>
</div>
</form>

Solution :

The easiest way to stop this is adding data check. And condition check at top of the method.category_description !== undefined. Btw, move the e.preventDefault() to top too.

Solution 2:

When you are clicking on Add Category button, it is triggering the addCategory along with the validation method.

The return value of validation method has no impact on triggering of addCategory.

This issue can be handled in following ways.

Call addCategory only when there is some valid data

<button type=”submit” @click=”category_description != undefined ? addCategory : ‘’” class=”btn btn-primary”> Add Category </button>

Call the validation method inside addCategory and then proceed.

Solution 3:

First of all do this:

- <button type=”submit” @click=”category_description !== undefined ? addCategory : ‘’” class=”btn btn-primary”> Add Category </button>
+ <button type=”submit” @click.prevent=”addCategory” class=”btn btn-primary”> Add Category </button>

and then in addCategory:

addCategory() {
if (!this.category_description) {
return;
} else {
// do the stuff here
}

}

[Vue.js] v-if with two conditions

there is the following code where v-if is always showing true even when doc.acceptance_letter = ‘’

<a
target=”_blank”
class=”has-text-link”
v-if=”doc.acceptance_letter!=null || doc.acceptance_letter!= ‘’ “
:href=”doc.acceptance_letter”
\>
view
</a>

hide this anchor tag when doc.acceptance_letter is null or empty.
Could anyone advise what I did wrong?

Solution :

the code will always show, because it will always be different from null or ‘’ (a variable can’t have two values simultaneously). As suggested on comments, you can just check v-if=”doc.acceptance_letter that will hide it in any falsy value, or do a v-if=”doc.acceptance_letter != null && doc.acceptance_letter != ‘’

<a
target=”_blank”
class=”has-text-link”
v-if=”doc.acceptance_letter
:href=”doc.acceptance_letter”
\>
view
</a>

Solution 2:

you have to use && instead of ||, to display the tag whendoc.acceptance_letter is not null and not empty.

<a
target=”_blank”
class=”has-text-link”
v-if=”doc.acceptance_letter!=null && doc.acceptance_letter!= ‘’ “
:href=”doc.acceptance_letter”>
view
</a>

Solution 3:

Missing a ‘=’

v-if=”doc.acceptance_letter!== null || doc.acceptance_letter!== ‘’ “

[Vue.js] Why do I have this error when I run the php artisan command?

there is a problem with artisan / composer, when I try to run for example: “php artisan” or perform a migration like: “php artisan make: migration” I get this error:

SQLSTATE [42S02]: Base table or view not found: 1146 Table

Solution :

You are calling it somewhere where it currently doesn’t exist as yet, most probably in one of the providers.

Import the Schema facade:

use Illuminate\Support\Facades\Schema;

Then wrap the code in the below statement:

if (Schema::hasTable(‘roles’)) {
// do something
}

[Vue.js] Cannot test Vue component with Jest Syntax error - Unexpected identifier

Project is created with @vue/cli@3.6.3. This is package.json

“scripts”: {
“serve”: “vue-cli-service serve”,
“build”: “vue-cli-service build”,
“lint”: “vue-cli-service lint”,
“test”: “npm run lint && npm run test:unit”,
“test:unit”: “jest –no-cache”
},
“dependencies”: {
“core-js”: “^2.6.5”,
“vue”: “^2.6.10”
},
“devDependencies”: {
“@vue/cli-plugin-babel”: “^3.6.0”,
“@vue/cli-plugin-eslint”: “^3.6.0”,
“@vue/cli-service”: “^3.6.0”,
“@vue/eslint-config-standard”: “^4.0.0”,
“babel-eslint”: “^10.0.1”,
“babel-jest”: “^24.7.1”,
“eslint”: “^5.16.0”,
“eslint-plugin-vue”: “^5.0.0”,
“jest”: “^24.7.1”,
“vue-jest”: “^3.0.4”,
“vue-template-compiler”: “^2.5.21”
},
“jest”: {
“transform”: {
“^.+\\.js$”: “babel-jest”,
“^.+\\.vue$”: “vue-jest”
}
}

This is my test

import Item from ‘../Item.vue’

describe(‘Item.vue’, () => {
test(‘sanity test’, () => {
console.log(Item)
})
})

with the component Item.vue.js being

<template>
<div>
Item
</div>
</template>

and this is the result

I get the error on the import statement. I thought this would be dealt by using the jest transformers, but it is not. What else do i need to add to pass the tests? The project url is this.

Solution :

You’ve never defined any Item component.
The only file you have in the project is Item.vue.js which contains only a template, there is no way for vuejs to import ‘Item’ since you’ve never declared the template as ‘Item’.

You should have a look to the VueJS Documentation about components ! In the first example you can see how the binding classname-template is done.

Then you will be able to import ‘Item’ from Item.vue.

[Vue.js] DB updates but Vuex store does not

when trying to submit a form that updates a user’s account settings. The form submits correctly to my API and the database entry updates. The component updates correctly initially, but when I refresh the page the component reverts back to its initial state, telling me that the Vuex store hasn’t updated correctly (I think?)

I’m sure it’s my ignorance on Vuex in general but I also feel that I’m pretty close. I’m basing this off of Jason Watmore’s excellent posts, this one specifically. Any suggestions would be much appreciated!

ProfilePage.vue.js (parent component)

<template>

<div class=’profile-container’>

<!– {/* User Info */} –>
<div class=’user-info-container’>
<h1 class=’user-headline’>{ account.user | prettyName }</h1>
<p>{ account.user | userLocation }</p>
</div>

<!– {/* Personal Details Form */} –>
<div class=’personal-details’ v-if=’activeSelection(0)’ >
<personal-form :account=’this.account.user’ v-on:listensubmit=’handleSubmit’/>
</div>

</div>

</template>

<script>
import { mapState, mapActions } from ‘vuex’;
import PersonalForm from ‘./_partials/PersonalForm’;

export default {
data: () => ({
tile : false,
}),
computed: {
…mapState({
account: state => state.account
}),
},
methods: {
…mapActions(‘account’, [‘update’]),
handleSubmit: function(user) {
this.$validator.validateAll().then((result) => {
if (result) {
this.submitted = true;
this.update(user);
}
});
},
},
components: {
PersonalForm,
}
};
</script>

PersonalForm.vue.js (child component)

<template>
<v-form ref=”personal-details-form” lazy-validation>
<v-container fluid grid-list-lg>
<v-layout row wrap>
<!– First Name –>
<v-flex xs12 md6>
<v-text-field
v-model=”user.firstName”
label=”First Name”
color=”primary”
prepend-inner-icon=”playlist_add”
outline
/>
</v-flex>

<!– Last Name –>
<v-flex xs12 md6>
<v-text-field
v-model=”user.lastName”
label=”Last Name”
color=”primary”
prepend-inner-icon=”playlist_add”
outline
/>
</v-flex>

<!– Email –>
<v-flex xs12 md6>
<v-text-field
v-model=’user.email’
v-validate=”‘required|email’”
:error-messages=”errors.collect(‘email’)”
label=’E-mail’
data-vv-name=’email’
color=’primary’
outline
prepend-inner-icon=”mail_outline”
/>
</v-flex>
</v-layout>

<v-layout justify-end>
<v-btn @click=”handleSubmit” color=”primary” :ripple=”false”>Submit</v-btn>
</v-layout>
</v-container>
</v-form>
</template>

<script>
import { mapState, mapActions } from ‘vuex’;

export default {
data: () => ({
submitted : false,
}),
computed: {
user () {
return {…this.account}
}
},
props: {
account: {
type : Object,
required: true,
},
listensubmit: {
type: Function,
}
},
methods: {
handleSubmit(event) {
this.$emit(‘listensubmit’, this.user);
}
},
}
</script>

account.module.js

import { userService } from ‘../_services’;
import { router } from ‘../_helpers’;

const user = JSON.parse(localStorage.getItem(‘user’));
const state = user
? { status: { loggedIn: true }, user }
: { status: {}, user: null };

const actions = {
update({ dispatch, commit }, user) {
commit(‘updateRequest’, user);

userService.update(user)
.then(
u => {
commit(‘updateSuccess’, user);
dispatch(‘alert/success’, ‘Account updated’, { root: true })
},
error => {
commit(‘updateFailure’, error);
dispatch(‘alert/error’, error, { root: true });
}
);
},
}

const mutations = {
updateRequest(state, user) {
state.status = { updating: true };
},
updateSuccess(state, user) {
state.status = { updated: true };
state.user = user;
},
updateFailure(state) {
state.status = { updated: false };
}
}

export const account = {
namespaced: true,
state,
actions,
mutations,
};

user.service.js

import config from ‘config’;
import { authHeader } from ‘../_helpers’;

export const userService = {
update,
};

function update(user) {
const requestOptions = {
method: ‘PUT’,
headers: { …authHeader(), ‘Content-Type’: ‘application/json’ },
body: JSON.stringify(user)
};

return fetch(`${config.apiUrl}/users/${user.id}`, requestOptions).then(handleResponse);
}

function handleResponse(response) {
return response.text().then(text => {
const data = text && JSON.parse(text);

if (!response.ok) {
if (response.status === 401) {
// auto logout if 401 response returned from api
logout();
location.reload(true);
}

const error = (data && data.message) || response.statusText;
return Promise.reject(error);
}

return data;
});
}

Solution :

Per Phil’s help in the comments of the original question, updating the user object in localStorage seems to have solved the problem.

[Vue.js] How do I pass a list of objects from controller to view?

there is some data (a list of datacontracts) in my controller. to show the fields/ values of that list inside my view. How do I do this properly?

This is the code inside my controller where I get the list data:

public List<ShipmentDataContract> Get(long shipmentServiceId)
{
Logging.Instance.Info($”Shipment request came in for shipment with ShipmentServiceId = {shipmentServiceId}”);
ShipmentQueryResult shipmentQueryResult = GetShipmentByShipmentServiceIdResult(shipmentServiceId);
Logging.Instance.Debug($”Shipment queried with ShipmentServiceId = {shipmentServiceId}”);
List<ShipmentDataContract> shipmentDataContracts = GetShipmentsFromResult(shipmentQueryResult);
Logging.Instance.Info($”Shipment retrieved for shipment with ShipmentServiceId = {shipmentServiceId}.”);
return shipmentDataContracts;
}

This method returns a list of datacontracts (only one in this case).

I made a test method inside the same controller as well within the Index method:

public ActionResult Index()
{
var shipmentDataTest = Get(94);

ViewBag.shipmentTestData = shipmentDataTest;

return View();
}

When I debug the backend, it returns the right shipment (with ID 94).

Now to show the shipment information within my view.

I made a variabele in my view:

<script>
var shipmentTestData = '@ViewBag.shipmentTestData‘;
</script>

And within my vue.js app file assigned the right values:

var vue.js = new Vue({
el: “#vueapp”,
components: [“error”],
data: {
shipmentTestData: shipmentTestData
}
});

Than when I call the data, it will not show the values, but a generic string.

<p>{ shipmentTestData }</p>

It returns this:

System.Collections.Generic.List`1[ShipmentDataContract]

Does someone know how to get this fixed? For some reason the variable that I assign is of format string which causes this issue I assume but how can I fix this?

Solution :

This is the proper way.

Model:

public class ShipmentData
{
Task<List<ShipmentDataContract>> Get(long shipmentServiceId)
{
return YourList;
}

Controller:

public ActionResult Index()
{
var shipmentDataTest = ShipmentData.Get(//index);

return View(shipmentDataTest);
}

View:

@Model YourShipmentModel
//here you can call Model.variable

Solution 2:

If you want to use the list as string you can send the result like

IList<string> someStrings = Get(94); // i assume than get method returns a list of “strings”
string joined = string.Join(“,”, someStrings );
ViewBag.shipmentTestData = joined;

Now you are sending to frotend the list “shipmentDataTest” as a comma separated list.
Let me know if this is what you are looking for. Greetings.

[Vue.js] Using commit in actions with promises returns 'Getters & Setters'

I’m using Vuex’s ‘actions’ to fetch from my database via an API.

It works well and there is a console.log(jsonResponse) which shows the correct data.

However, when I add commit(‘updateQuestions’, jsonResponse) to the picture, the return values for all of the fields are “Setters & Getters”

store.js:

mutations: {
updateQuestionsInit: (state, payload) => {
state.questions.init = payload
}
},
actions: {
onInit: async ({commit}) => {
try {
let response = await fetch(‘http://localhost:8080/api/mongo/initialforms')

if (response.ok) {
let jsonResponse = await response.json()
console.log(jsonResponse)
// Omitting the below line means it works.
commit(‘updateQuestionsInit’, jsonResponse)
}
}
catch (error) {
console.log(‘ERROR’, error)
}
}
}

Results

Expected Results

[
{
id: 0,
type: “dropdown”,
value: “sku”,
}, …
]

Actual Results

[
{
id: Getter & Setter,
type: Getter & Setter
value: Getter & Setter,

}, …

]

Why does this happen and how would it be rectified?

Solution :

Are you using Firefox? Others experienced similar issues but for them it seemed to work on chrome. Apparently, Firefox shows “Setters & Getters” in the console but the underlying values are correct.

-> Switch to Chrome and see if the issue remains.

References

vue.js Getter & Setter instead of the actual values in backend response

https://discourse.mozilla.org/t/webextension-apis-made-as-getter-setter-lazily-evaluating-to-functions-beware-of-mocking-for-unit-tests/30849