- 创建vue实例
import { createApp } from 'vue' import App from './App.vue' createApp(App).mount('#app')
- vue3 新建元素 (ref、reactive、toRefs)
//ref 创建 字符串形式数据 ((vue2 是写在data中)) const sendVal = ref(""); const name = ref("年糕"); const age = ref(20); // reactive 创建对象数据 const msg = reactive({ name: "张三", age: 18, dbZhang: computed(() => { return `双倍年纪${msg.age * 2}`; }), }); // 函数创建(vue2 是写在methods中) function add() { console.log(age); age.value += 1; } //最重要的,需要将这些新创建的 return 出来 setup() { //在setup 中创建数据与函数 (将上面都写在setup中) .... .... .... return { name, age, dbAge, add, ...toRefs(msg), add02, sendMsg, sendVal }; }
- vue3 props 传参
// 父组件 <HelloWorld child="我是传的参数" @accept="sendMsg"></HelloWorld>
//父组件接收子组件的传参
function sendMsg(params) { sendVal.value = params; // senVal 为上面创建的空字符串数据,赋值时为 sendVal.value msg.name = params; }
也需要将sendMsg 在setup 函数中 return 出去
//子组件 props: { child: String, },
setup(props, context) {
const childs = ref(props.child);
function send() {
context.emit("accept", "子组件传参"); //因为没有this 所以需要 context }
return { childs, send }; },
- watch 进行数据监听
watch在监听 ref 类型时和监听reactive类型时watch函数的写发有所不一样。
watch(
//watch 监听 reactive 类型 () => msg.age, (newVal, oldVal, clean) => { console.log(msg.name + newVal, oldVal); clean(() => { console.log("clean"); }); }, name, //watch在监听 ref 类型时: (newVal, oldVal) => { console.log(newVal, oldVal); }, );
watchEffect 它与 watch 的区别主要有以下几点:
- 不需要手动传入依赖
- 每次初始化时会执行一次回调函数来自动获取依赖
- 无法获取到原值,只能得到变化后的值
watchEffect(() => { console.log(state.count) console.log(state.name) /* 初始化时打印: 0 zs 1秒后打印: 1 ls */ })
watch和watchEffect监听器在同一个页面中都可以使用多次,对于分别监听多个变量的时候
- vue3 计算属性 computed
const dbAge = computed(() => { return `我的年纪${age.value * 2}`; }); //直接写在变量声明中 const msg = reactive({ name: "张三", age: 18, dbZhang: computed(() => { return `双倍年纪${msg.age * 2}`; }), });