修改 props 中的数据的问题:
在 Shop.vue 组件中使用 props 的数组写法接收参数 并在 methods 中创建 add 方法 点击让商品数量加一。
<template>
<div>
<h2>商品名称:{{ name }}</h2>
<strong>商品价格:¥{{ price }}</strong>
<p>商品数量:{{ num }}</p>
<button @click="add">点击商品数量加1</button>
<hr />
</div>
</template>
<script>
export default {
name: "Shop",
props: ['name', 'price', 'num'],
methods: {
add() {
this.num++;
}
}
}
</script>
然后在 Home.vue 页面正常引入传参 将 num 用 v-bind 绑定 避免传递字符串类型。
<template>
<div>
<h2>商品列表</h2>
<hr />
<Shop name="草莓" price="99" :num="50"></Shop>
<Shop name="苹果" price="30" :num="30"></Shop>
<Shop name="葡萄" price="56" :num="20"></Shop>
</div>
</template>
<script>
import Shop from "../components/Shop";
export default {
name: 'Home',
components: { Shop }
}
</script>
注:点击后虽然商品数量能够增加 但控制台也会报错提醒 因为这么做会出现一些莫名其妙的问题 所以 Vue 不推荐直接更改 props 中的数据。
正确修改方式:如果需要修改接收到的参数 推荐在 data 中创建一个新数据接收 props 中的数据然后使用这个新数据即可。
<template>
<div>
<h2>商品名称:{{ name }}</h2>
<strong>商品价格:¥{{ price }}</strong>
<p>商品数量:{{ myNum }}</p>
<button @click="add">点击商品数量加1</button>
<hr />
</div>
</template>
<script>
export default {
name: "Shop",
props: ['name', 'price', 'num'],
data() {
return {
myNum: this.num
}
},
methods: {
add() {
this.myNum++;
}
}
}
</script>
注:这样就可以解决这个问题啦 因为 props 的优先级要高于 data 所以我们能在 data 中使用 props 中的数据 另外 props 的数据也是在组件实例上绑定的 所以需要用 this 调用。
需要注意 data 中的数据名不要和 props 中的数据名一样 否则会报错。例:
<template>
<div>
<h2>商品名称:{{ name }}</h2>
<strong>商品价格:¥{{ price }}</strong>
<p>商品数量:{{ num }}</p>
<button @click="add">点击商品数量加1</button>
<hr />
</div>
</template>
<script>
export default {
name: "Shop",
props: ['name', 'price', 'num'],
data() {
return {
num: 9
}
},
methods: {
add() {
this.num++;
}
}
}
</script>
注:如果 data 和 props 中存在一样的数据名 默认会使用 props 中的数据。
原创作者:吴小糖
创作时间:2023.3.29