I'm trying to use a random string (UUID v4) with vue-uuid for current items and items added to the list in the future (this is a to-do list type app) but I'm not sure what to correct syntax is.
I installed it and added it to my project in main.js:
import UUID from 'vue-uuid';
Vue.use(UUID);
However, I don't know how to use it in my Vue component. This is what I tried:
Template:
<transition-group
name="list"
enter-active-class="animated bounceInUp"
leave-active-class="animated bounceOutDown"
>
<li v-for="item in skills" :key="uuid">{{ item.skill }}</li>
</transition-group>
Script:
import { uuid } from 'vue-uuid';
export default {
name: 'Skills',
data() {
return {
uuid: uuid.v4(),
skill: '',
skills: [{ skill: 'Vue.js' }, { skill: 'React' }]
};
},
};
For :key="uuid", I get an error saying Expected 'v-bind:key' directive to use the variables which are defined by the 'v-for' directive (vue/valid-v-for). I also tried changing it to :key="item.uuid" which makes that error go away, but then the list doesn't appear.
project repo (based on this Udemy Vue crash course)
Try this:
<template>
<div id="app">
<p :key="item.uuid" v-for="item in skills">{{ item.skill }}</p>
</div>
</template>
<script>
import { uuid } from "vue-uuid";
export default {
name: "App",
data() {
return {
skills: [
{ uuid: uuid.v4(), skill: "Vue.js" },
{ uuid: uuid.v4(), skill: "React" }
]
};
}
};
</script>
This is a working demo: https://codesandbox.io/s/nifty-sutherland-b0k9q
UPDATED
to be dynamic
There are two moments that you could add the uuid to each element in the skills array:
1 When adding a new skill:
addSkill() {
this.$validator.validateAll().then(result => {
if (result) {
this.skills.push({ uuid: uuid.v4(), skill: this.skill });
this.skill = "";
}
});
}
2 When rendering them, in this case, you might use a computed property like so:
import { uuid } from 'vue-uuid';
export default {
name: 'Skills',
data () {
return {
skill: '',
skills: [{ skill: 'Vue.js' }, { skill: 'React' }]
};
},
computed: {
computedSkills () {
return this.skills.map(skill => {...skill, uuid: uuid.v4() })
}
}
};
And then using the computedSkills computed property for rendering rather than the skills property. Something like:
<li v-for="item in computedSkills" :key="item.uuid">{{ item.skill }}</li>
Related
Recently I came across vue-error-boundary which I like the idea of very much and would like to implement it into my own projects.
I want to use vue-error-boundary features to load a component with an error instead of crashing my app. However for some reason all I can do is get the on-error prop to work, component GETS loaded but with a warning and the App still Crushes.
For Reproduction purpose:
CodeSandbox
I get following error:
Vue warn]: Unhandled error during execution of render function
at <ImUnstable>
at <VErrorBoundary on-error=fn<bound TriggerMe> fall-back=
{render: ƒ render(), __hmrId: "6505c1f8", __file: "src/components/ContactError.vue"}
>
CODE:
App.vue:
<template>
<VErrorBoundary :on-error="TriggerMe" :fall-back="fallBack">
<ImUnstable />
</VErrorBoundary>
</template>
<script>
import { markRaw } from "vue";
import VErrorBoundary from "vue-error-boundary";
import ImUnstable from "#/components/ImUnstable.vue";
import ContactError from "#/components/ContactError";
export default {
components: {
ImUnstable,
VErrorBoundary,
},
name: "App",
data() {
return {
fallBack: markRaw(ContactError),
};
},
methods: {
TriggerMe() {
console.log("It Triggered");
},
},
};
</script>
ImUnstable.vue:
<template>
<div v-for="user in users" :key="user.id">
<p>
{{ user.name }}
{{ makeLarge(user.surname) }}
{{ user.age }}
</p>
</div>
</template>
<script>
export default {
errorCaptured() {
console.log("let me see");
},
data() {
return {
users: [
{ id: 1, name: "Luke", surname: "Skywalker", age: "22" },
{ id: 2, name: "Han", surname: {}, age: "35" },
],
};
},
methods: {
makeLarge(data) {
return data.toUpperCase();
},
},
};
</script>
ContactError.vue:
<template>
<div>
<p>There was an issue obtaining contact's information.</p>
</div>
</template>
In my own component, i'm using SfComponentSelect (here in official docs)
When I click on option of select, selected option not show above the label "MySelect", this happen otherwise on sample inside the official docs.
This is my CustomComponent.vue
<template>
<SfComponentSelect label="MySelect">
<SfComponentSelectOption
v-for="option in optionsList"
:key="option.value"
:value="option.value"
class="sort-by__option"
>{{ option.label }}</SfComponentSelectOption>
</SfComponentSelect>
</template>
<script>
import { SfComponentSelect } from '#storefront-ui/vue';
export default {
name: "CustomComponent",
components: {
SfComponentSelect
},
data(){
return {
optionsList: [
{
value: "opt-1",
label: "Option 1",
},
{
value: "opt-2",
label: "Option 2",
}
]
}
}
};
</script>
After struggling on problem, i've found a solution for this problem.
Create new component (called: MyNewComponent) defining SfComponentSelect as mixins and copying from template and scss from SfComponentSelect.
Defining for MyNewComponent a new props and html for this
Using MyNewComponent as below
<SelectStore :label="name"
:size="pdvLists.length"
#change="changeLabel"
:my-new-label="myNewLabel"
persistent>
<SfComponentSelectOption
v-for="option in options"
:key="option.value"
:value="option.value"
class="sort-by__option"
>{{ option.name }}</SfComponentSelectOption>
</SelectStore>
<script>
import MyNewComponent from './MyNewComponent';
export default {
name: "ComponentBlaBla",
components: {
MyNewComponent
},
data() {
return {
options: [
{
value: "opt1",
name: "Opt1"
},
{
value: "opt2",
name: "Opt2"
}
],
myNewLabel: ''
}
},
methods: {
changeLabel(value){
// change something
let selectedOption = this.options.filter((item) => value === item.value);
this.myNewLabel = selectedOption[0].name;
}
}
};
</script>
I want to take data from js files classified as categories such as 'Delivery' and 'Cafe' and deliver different data to different pages.
I thought about how to import it using map(), but I keep getting errors such as 'products' is not defined.'
It must be done, but it is not implemented well with javascript and react weak. If you know how to do it, I'd appreciate it if you could let me know.
Products.js
export const Product = [
{
Delivery: [
{
id: '101',
productName: '허니랩',
summary: '밀랍으로 만든 친환경 식품포장랩 허니랩.',
description:
'~~',
images: ['3k7sH9F'],
companyName: '허니랩',
contact: '02-6082-2720',
email: 'lesslabs#naver.com',
url: 'https://honeywrap.co.kr/',
},
{
id: '102',
productName: '허니포켓',
summary: '밀랍으로 만든 친환경 식품포장랩 허니랩. 주머니형태.',
description:
"~~",
images: ['4zJEqwN'],
companyName: '허니랩',
contact: "02-6082-2720",
email: "lesslabs#naver.com",
url: "https://honeywrap.co.kr/",
},
],
},
{
HouseholdGoods: [
{
id: '201',
productName: '순둥이',
summary: '아기용 친환경 순한 물티슈',
description:
'~',
images: ['4QXJJaz'],
companyName: '수오미',
contact: '080-000-3706',
email: 'help#sumomi.co.kr',
url: 'https://www.suomi.co.kr/main/index.php',
},
{
id: '202',
category: ['HouseholdGoods'],
productName: '순둥이 데일리',
summary: '친환경 순한 물티슈',
description: '품질은 그대로이나 가격을 낮춘 경제적인 생활 물티슈',
images: ['OMplkd2'],
companyName: '수오미',
contact: '080-000-3706',
email: 'help#sumomi.co.kr',
url: 'https://www.suomi.co.kr/main/index.php',
},
],
},
];
Delivery.js
(The file was named temporarily because I did not know how to classify and deliver data without creating a js file separately.)
import React from "react";
function Delivery(
productName,
companyName,
contact,
email,
url,
summary,
description
) {
return (
<div className="Product">
<div className="Product__data">
<h3 className="Product__name">{productName}</h3>
<h4>{companyName}</h4>
<h5>Contact: {contact}</h5>
<h5>Email: {email}</h5>
<h5>URL: {url}</h5>
<p className="Product__summary">{summary}</p>
<p className="Proudct__descriptions">{description}</p>
</div>
</div>
);
}
export default Delivery;
Category.js
import React from "react";
import Delivery from "./Delivery";
import { Product } from "./Products";
class Category extends React.Component {
render() {
state = {
products: [],
};
this.setState(_renderProduct());
return <div>{products ? this._renderProduct() : "nothing"}</div>;
}
_renderProduct = () => {
const { products } = this.state;
const renderProducts = products.map((product, id) => {
return (
<Delivery
productName={Product.productName}
companyName={Product.companyName}
contact={Product.contact}
email={Product.email}
url={Product.url}
summary={Product.summary}
description={Product.description}
/>
);
});
};
}
export default Category;
Sorry and thank you for the long question.
There are quite a few different problems I've found.
First is that you call setState inside render in the Category component, this causes an infinite loop. Instead call setState inside a lifecycle method like componentDidMount or use the useEffect hook if using functional components.
Another problem is that state in Category is also defined inside render. In class components you would normally put this in a class constructor outside of render.
In your setState call you refer to _renderProduct(), this should be this._renderProduct() instead.
Now the main problem here is the structure of your data / how you render this structure.
Products is an array of objects where each object either has a Delivery or HouseholdGoods property which is an array of products. I would advise you to change this structure to something more like this:
export const Product = {
Delivery: [
{
id: "101",
},
{
id: "102",
},
],
HouseholdGoods: [
{
id: "201",
},
{
id: "202",
},
],
};
or this:
export const Product = [
{ id: "101", productType: "Delivery" },
{ id: "102", productType: "Delivery" },
{ id: "201", productType: "HouseholdGoods" },
{ id: "202", productType: "HouseholdGoods" },
];
I personally prefer the second structure, but I've implemented the first as this seems to be what you were going for:
class Category extends React.Component {
constructor(props) {
super(props);
this.state = {
products: null,
};
}
componentDidMount() {
this.setState({ products: Product });
}
render() {
const { products } = this.state;
return (
<div>
{products
? Object.keys(products).map((productKey) => {
return (
<div key={productKey}>
{products[productKey].map((product) => {
return (
<Delivery
key={product.id}
productName={product.productName}
companyName={product.companyName}
contact={product.contact}
email={product.email}
url={product.url}
summary={product.summary}
description={product.description}
/>
);
})}
</div>
);
})
: "no products"}
</div>
);
}
}
We need a nested loop here, because we need to map over each property key and over the array of objects inside each property. If you use the other structure for Product I've shown, you can simply map over Product without needing two loops.
Now the last important problem was that you weren't destructuring the props inside your Delivery component, instead you should do something like this:
function Delivery({
productName,
companyName,
contact,
email,
url,
summary,
description,
}) {
return (
<div className="Product">
<div className="Product__data">
<h3 className="Product__name">{productName}</h3>
<h4>{companyName}</h4>
<h5>Contact: {contact}</h5>
<h5>Email: {email}</h5>
<h5>URL: {url}</h5>
<p className="Product__summary">{summary}</p>
<p className="Proudct__descriptions">{description}</p>
</div>
</div>
);
}
Example Sandbox
I am passing a clone of an object from a parent component to a child component using props, but when I change the value of the status property in the object of the parent component the child component gets notified and chenges the value of the status property in the "cloned" object.
I've read about Object.assign() method and that it only does shallow copying but the strange thing is that my object properties are of primitive type String meaning they should be copied by value not by reference, I even tried assigning the values manually and tried the JSON way as demonstrated below but nothing works as I expected.
Parent Component: AppServers
<template>
<div>
<AppServerStatus v-for="server in servers" :serverObj="JSON.parse(JSON.stringify(server))">
</AppServerStatus>
<hr>
<button #click="changeStatus()">Change server 2</button>
</div>
</template>
<script>
import AppServerStatus from './AppServerStatus';
export default {
name: "AppServers",
components: {
AppServerStatus
},
data() {
return {
servers: [
{
name: 'server1',
status: 'Critical'
},
{
name: 'server2',
status: 'Normal'
},
{
name: 'server3',
status: 'abnormal'
},
{
name: 'server4',
status: 'idle'
},
{
name: 'server5',
status: 'Good'
},
],
serverTmp: {}
}
},
methods: {
changeStatus(){
this.servers[1].status = 'Active';
}
}
}
</script>
Child Component: AppServerStatus
<template>
<div>
<h3>Server Name: {{ serverObj.name }}</h3>
<p>Server Status: {{ serverObj.status }}</p>
<hr>
</div>
</template>
<script>
export default {
name: "AppServerStatus",
data() {
return {
status: 'Critical'
}
},
props: [
'serverObj'
]
}
</script>
I expect the value of status property in the object of the child component to stay Normal when I execute changeStatus() in the parent component but it changes also.
Create a new object from the serverObj prop on created or mounted to prevent unwanted reactivity.
<template>
<div>
<h3>Server Name: {{ server.name }}</h3>
<p>Server Status: {{ server.status }}</p>
<hr>
</div>
</template>
<script>
export default {
name: 'AppServerStatus',
data() {
return {
status: 'Critical',
server: {
name: '',
status: ''
}
}
},
props: [
'serverObj'
],
mounted() {
this.server = {
name: this.serverObj.name,
status: this.serverObj.status
};
}
}
</script>
I'm new to Vue and I wanted to learn Veux by building a simple CRUD application with firebase. So far I've been able to figure things out (though if you see something badly coded, I would appreciate any feedback) but I can't seem to figure out how to remove an item. The main problem is that I can't reference it properly. I'm getting [object Object] in my reference path but when I log it I get the correct id.
Firebase Flow:
So I'm making a reference to 'items', Firebase generates a unique key for each item and I added in an id to be able to reference it, though I could also reference it by the key.
I've been able to do this without using Veux and just component state but I've been trying for hours to figure out what I'm doing wrong.
I'm also getting this error:
Store.js
import Vue from 'vue'
import Vuex from 'vuex'
import database from './firebase'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
items: []
},
mutations: {
RENDER_ITEMS(state) {
database.ref('items').on('value', snapshot => {
state.items = snapshot.val()
})
},
ADD_ITEM(state, payload) {
state.items = payload
database.ref('items').push(payload)
},
REMOVE_ITEM(index, id) {
database.ref(`items/${index}/${id}`).remove()
}
},
// actions: {
// }
})
Main.vue
<template>
<div class="hello">
<input type="text" placeholder="name" v-model="name">
<input type="text" placeholder="age" v-model="age">
<input type="text" placeholder="status" v-model="status">
<input type="submit" #click="addItem" />
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item.name }}
{{ item.age }}
{{ item.status }}
<button #click="remove(index, item.id)">Remove</button>
</li>
</ul>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
import uuid from 'uuid'
export default {
name: 'HelloWorld',
created() {
this.RENDER_ITEMS(this.items)
},
data() {
return {
name: '',
age: '',
status: '',
id: uuid(),
}
},
computed: {
...mapState([
'items'
])
},
methods: {
...mapMutations([
'RENDER_ITEMS',
'ADD_ITEM',
'REMOVE_ITEM'
]),
addItem() {
const item = {
name: this.name,
age: this.age,
status: this.status,
id: this.id
}
this.ADD_ITEM(item)
this.name = ''
this.age = ''
this.status = ''
},
remove(index, id) {
console.log(index, id)
this.REMOVE_ITEM(index, id)
}
}
}
</script>
The first argument to your mutation is always the state.
In your initial code:
REMOVE_ITEM(index, id) {
database.ref(`items/${index}/${id}`).remove()
}
index is the state object, which is why you are getting [object Object] in the url.
To fix your issue, pass an object to your mutation and change it to:
REMOVE_ITEM(state, {index, id}) {
database.ref(`items/${index}/${id}`).remove()
}
And when you are calling your mutation with the remove method, pass an object as well:
remove(index, id) {
console.log(index, id)
// pass an object as argument
// Note: {index, id} is equivalent to {index: index, id: id}
this.REMOVE_ITEM({index, id})
}