vue修改props數(shù)據(jù)報錯的問題及解決
修改props中的數(shù)據(jù)的問題
在 Shop.vue 組件中使用 props 的數(shù)組寫法接收參數(shù) 并在 methods 中創(chuàng)建 add 方法 點擊讓商品數(shù)量加一。
<template> <div> <h2>商品名稱:{{ name }}</h2> <strong>商品價格:¥{{ price }}</strong> <p>商品數(shù)量:{{ num }}</p> <button @click="add">點擊商品數(shù)量加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>
注:點擊后雖然商品數(shù)量能夠增加 但控制臺也會報錯提醒 因為這么做會出現(xiàn)一些莫名其妙的問題 所以 Vue 不推薦直接更改 props 中的數(shù)據(jù)。
正確修改方式
如果需要修改接收到的參數(shù) 推薦在 data 中創(chuàng)建一個新數(shù)據(jù)接收 props 中的數(shù)據(jù)然后使用這個新數(shù)據(jù)即可。
<template> <div> <h2>商品名稱:{{ name }}</h2> <strong>商品價格:¥{{ price }}</strong> <p>商品數(shù)量:{{ myNum }}</p> <button @click="add">點擊商品數(shù)量加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 的優(yōu)先級要高于 data 所以我們能在 data 中使用 props 中的數(shù)據(jù) 另外 props 的數(shù)據(jù)也是在組件實例上綁定的 所以需要用 this 調(diào)用。
需要注意 data 中的數(shù)據(jù)名不要和 props 中的數(shù)據(jù)名一樣 否則會報錯。
例:
<template> <div> <h2>商品名稱:{{ name }}</h2> <strong>商品價格:¥{{ price }}</strong> <p>商品數(shù)量:{{ num }}</p> <button @click="add">點擊商品數(shù)量加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 中存在一樣的數(shù)據(jù)名 默認(rèn)會使用 props 中的數(shù)據(jù)。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
一篇文章帶你吃透Vue生命周期(結(jié)合案例通俗易懂)
這篇文章主要給大家介紹了關(guān)于如何通過一篇文章帶你吃透Vue生命周期,文章通過結(jié)合案例更加的通俗易懂,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2022-02-02Vue+axios+WebApi+NPOI導(dǎo)出Excel文件實例方法
在本篇文章里小編給大家整理關(guān)于Vue+axios+WebApi+NPOI導(dǎo)出Excel文件的知識點以及實例代碼,需要的朋友們參考下。2019-06-06

vue 對axios get pust put delete封裝的實例代碼