setup計算屬性和鉤子函式
阿新 • • 發佈:2022-05-11
1.setup 定義計算屬性
<script src="https://unpkg.com/vue@next"></script> <body> <div id="app"> <h3>setup-computed計算屬性</h3> obj.b: {{obj.b}} <br> <p>計算屬性:2倍:{{doubleB}} </p> <p>計算屬性:0.5倍:{{halfB}} </p> <p>計算屬性:3倍:{{triangleB}} </p> <button @click="obj.b+=1">原值+1</button> </div> <script> const { createApp, reactive, computed }= Vue const app = createApp({ data() { return {} }, // 步驟: // 1. 在setup中通過computed來建立函式, // 2. 匯出 setup() { // reactive: 會對物件進行包裝 const obj = reactive({b: 1}) // 通過computed來建立計算屬性 const doubleB = computed(()=>{ return 2*obj.b }) const triangleB= computed(()=>{ return 3*obj.b }) return { obj, doubleB, triangleB } }, computed: { halfB () { return this.obj.b / 2 } } }) app.mount("#app") </script> </body>
通過computed(回撥)的方式來計算屬性,然後在setup中返回即可。
2.在setup中寫watch
<script src="https://unpkg.com/vue@next"></script> <div id="app"> <h3>setup-watch</h3> {{obj.b}}, {{a}}<br> <button @click="obj.b+=1">原值b+1</button> <button @click="a+=1">原值a+1</button> </div> <script> const { createApp, reactive, watch, ref } = Vue const app = createApp({ data() { return { } }, setup() { // reactive: 會對物件進行包裝 const obj = reactive({b: 1}) const a = ref(0) // 通過watch來監聽 watch(() => obj.b ,()=>{ console.log(`obj.b變化了`) }) watch(a, ()=>{ console.log(`a變化了`) }) return { obj, a } } }) app.mount("#app") </script>
3.在setup中寫鉤子函式
<script src="https://unpkg.com/vue@next"></script> <body> <div id="app"> <h3>setup-鉤子函式</h3> </div> <script> const { createApp,onMounted} = Vue const app = createApp({ data() { return { } }, setup() { onMounted(()=>{ console.log('setup, mounted1')}) onMounted(()=>{ console.log('setup, mounted2')}) }, mounted () { console.log('mounted') } }) app.mount("#app") </script>