在公司里由于某些不可抗力因素导致Vue2的项目无法升级Vue3,所以只能把现有的项目修改为Pinia,正好发现Vue2也可以使用Setup语法糖,网上查了些资料都不是很全面,自己大概整理了个例子放出来,送给和我一样有需要的同学。
<template>
<div>
<div>{{ num }}</div>
<div>{{ count }}</div>
<div>{{ double }}</div>
<div>{{ message }}</div>
<div>{{ bluetoothEnabled }}</div>
<div>
<button @click="changeNum">点我1</button>
</div>
<div>
<button @click="changeBluetoothEnabled">点我2</button>
</div>
<div>
<button @click="addCount">点我3</button>
</div>
</div>
</template>
<script setup>
import { mainStore } from '@/store';
import { storeToRefs } from 'pinia';
import { watch, ref, computed } from 'vue';
import { onMounted, onUnmounted } from 'vue';
const store = mainStore();
const { bluetoothEnabled } = storeToRefs(store);
const num = ref(0);
const changeNum = () => {
num.value++;
};
const changeBluetoothEnabled = () => {
bluetoothEnabled.value = !bluetoothEnabled.value;
};
watch(bluetoothEnabled, (newVal, oldVal) => {
console.log('----', newVal);
});
const count = ref(0);
const double = computed(() => count.value * 2); // 返回值的函数
const message = computed({
get: () => `Count is ${count.value}`, // get方法
set: val => {
count.value = val;
} // set方法
});
const addCount = () => {
count.value++;
};
onMounted(() => {
console.log('组件创建了');
});
onUnmounted(() => {
console.log('组件销毁了');
});
</script>
另外,watch的对象并不一定非要把对象通过storeToRefs进行解构,也可以使用下面的方式直接监听
watch(()=>store.bluetoothEnabled, (newVal, oldVal)=>{
console.log('++++', newVal);
})