修改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 中的数据。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论