VUE3.0 学习笔记-创建数据,props传参、watch监听、计算属性computed

  • 创建vue实例
1
2
3
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
  •  vue3 新建元素 (ref、reactive、toRefs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//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 传参
1
2
3
4
5
6
// 父组件
 
 <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 进行数据监听
1
2
3
4
5
6
7
8
9
10
11
12
13
watch在监听 ref 类型时和监听reactive类型时watch函数的写发有所不一样。 <br>watch(<br>    //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 的区别主要有以下几点:

  1. 不需要手动传入依赖
  2. 每次初始化时会执行一次回调函数来自动获取依赖
  3. 无法获取到原值,只能得到变化后的值
1
2
3
4
5
6
7
8
9
10
11
12
watchEffect(() => {
          console.log(state.count)
          console.log(state.name)
          /*  初始化时打印:
                  0
                  zs
 
            1秒后打印:
                  1
                  ls
          */
          })

  watch和watchEffect监听器在同一个页面中都可以使用多次,对于分别监听多个变量的时候

  •  vue3 计算属性 computed
1
2
3
4
5
6
7
8
9
10
11
const dbAge = computed(() => {
      return `我的年纪${age.value * 2}`;
   }); //直接写在变量声明中
 
const msg = reactive({
      name: "张三",
      age: 18,
      dbZhang: computed(() => {
        return `双倍年纪${msg.age * 2}`;
      }),
    });

  

  

posted @   沁猿春  阅读(1901)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示