有時候我發現在學一門新知識的時候發現,直接看教程總是看不進去,然后在項目中碰到了在回頭看發現反而理解得更好些,記得也更牢些。比如標題中這個知識點,現在項目中有用到,因此在這里做個總結。
你可以像這樣實現對vuex全局狀態的監聽
computed: { f1() { return this.$store.state.xxxx } }, watch: { f1(curVal, oldVal) { //這里的curVal就是需要監聽的值 } }
computed 里一般寫個函數,這個函數里一定是return一個結果。這里你可以直接用f1作為本組件監聽$store.state.xxxx,也可以在本組件里聲明一個變量然后再通過watch監聽,將watch中的curVal賦值給該變量從而達到使用的目的。
鏈接:https://www.jianshu.com/p/b5365c05882b
watch監聽和雙向綁定的案例
父組件:
<template> <div class="ctn"> <!-- 屬性綁定傳值給子組件, 自定義事件接收子組件的值 --> <Watchzi :number1="num1" @num1change="num1change" /> <p> 父組件:{{num1}}</p> </div> </template> <script> import Watchzi from './watchZi.vue' export default { components: { Watchzi }, data() { return{ num1:'100' } }, methods: { num1change(val){ this.num1 = parseFloat(val) } } } </script>
子組件:
<template> <div class="ctn"> <input type="text" v-model="dnumber1"> <!-- v-model:是input事件 和value屬性綁定的結合 --> <!-- <input type="text" :value="dnumber1" @input="num1Input" /> --> <p>{{name}}</p> </div> </template> <script> export default { props: { number1: Number, number2: Number }, data() { return{ dnumber1:this.number1, dnumber2: this.number2, name: '1' } }, watch: { // 監聽屬性變化的時候,並向父組件傳值 dnumber1(newValue){ this.dnumber2 = newValue * 100; // 向父組件傳值 this.$emit('num1change', newValue); }, // 你監聽什么屬性就寫什么名字,比如監聽name屬性,就寫name方法 name(newValue) { // 監聽到屬性的改變,就可以做其他事情了 console.log(newValue) } } } </script>