【发布时间】:2020-09-28 20:17:32
【问题描述】:
我的父组件 App.vue 中有一个按钮,并且想在我的子组件上收听 buttonclick 并在每次单击按钮时传递一个递增的数字。目前我正在将值作为道具传递,并正在使用watch: { 观察我的子组件的变化@
这很好用。但是,由于我对 vue 很陌生,我想知道是否有更好的方法或者这是推荐的方法?
App.vue
<template>
<div id="app">
<button @click="myMethod">To child</button>
<Mycomponent :myProp="count" />
</div>
</template>
<script>
import Mycomponent from "./components/Mycomponent";
export default {
name: "App",
components: {
Mycomponent
},
data() {
return {
count: 0
};
},
methods: {
myMethod() {
this.count++;
}
}
};
</script>
Mycomponent.vue
<template>
<div>
{{myNumber}}
</div>
</template>
<script>
export default {
name: "Mycomponent",
props: {
myProp: {
type: Number
}
},
data() {
return {
myNumber: 0
};
},
watch: {
myProp: {
deep: true,
immediate: true,
handler(newValue) {
try {
console.log("Print my value in the consule: ", newValue);
this.myNumber = newValue
} catch (err) {
console.log("no data yet ...");
}
}
}
}
};
</script>
在子组件中获得道具的更新示例
<template>
<div>
// what if I dont want to display myProp in the template? Just store the data
{{myProp}}
<button @click="myMethod">Method</button>
</div>
</template>
<script>
export default {
name: "Mycomponent",
props: {
myProp: {
type: Number
}
},
methods: {
myMethod() {
console.log("print myProp ", this.myProp);
}
}
};
</script>
但是,如果我不想显示该值怎么办。只是将道具用作数据?
【问题讨论】:
标签: javascript vue.js components