Web 框架Vue3

发布时间 2023-10-06 00:38:41作者: havelearned

setUP函数

<template>
  <div>vue3 写法:{{ value1 }}</div>
  <br />
  <div>vue2 写法:{{ value2 }}</div>
  <br />
  <div>
    vue3 中的对象:
    <h5 v-for="(item, index) in obj" :key="index">
      {{ item }}
    </h5>
  </div>

  <br />
  <div>
    vue3 中的funcation:
    <button @click="fun1">点击</button>
    <button @click="value3">箭头函数</button>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      value2: "vue2的写法",
    };
  },
  setup() {
    console.log("自动执行的函数");
    const value1 =
      "定义的常量和变量都在setup函数中,定义的函数变量都需要返回,否则变量常量无法使用";
    console.log(value1);

    const obj = ["setup", "中的", "对象"];
    function fun1() {
      alert("setup中的函数 fun1");
    }

    // 变量指向一个函数
    const value3 = () => {
      alert("箭头函数 value3");
    };

    return { value1, obj, fun1, value3 };
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped></style>


组合式API

ref 常用于:基础数据类型

<template>
  <div>
    <h1>姓名:{{ name }}</h1>
    <h1>年龄:{{ age }}</h1>
    <h1 v-for="(item, index) in obj" :key="index">数组:{{ item }}</h1>

    <h1 v-for="(item, index) in obj2" :key="index">
      对象:
      <h5 v-for="(item2, index2) in item" :key="index2">
        {{ item2 }}
      </h5>
    </h1>

    <button @click="fun1">点击更变视图</button>
  </div>
</template>

<script>
import { ref } from "vue";
export default {
  setup() {
    const name = ref("张三");
    const age = ref(32);
    const obj = [1, 2, 3, 4, 5, 6, 7, 8];
    const obj2 = ref({
      taobao: "淘宝",
      tamll: ["天猫", 1, 3, 4],
    });

    const fun1 = () => {
      name.value = "马化腾";
      age.value = 100;
      obj2.value.taobao = "淘宝马云的";
      obj2.value.tamll = "天猫马云的";
    };

    return { name, age, obj, obj2, fun1 };
  },
};
</script>
<style scoped></style>

reactive 常用于:数组对象

<template>
  <div>
    <table>
      <th>数组</th>
      <td v-for="(item, index) in obj1" :key="index">{{ item }}</td>
      <th>对象</th>
     
        <h5>姓名: {{ obj2.name }}</h5>
        <h5>年龄: {{ obj2.age }}</h5>
        <h5>陶波: {{ obj2.taobao }}</h5>

        <h5 v-for="(item2, index2) in obj2.por.a.b" :key="index2">
           {{ item2 }}
        </h5>
     
    </table>
    <button @click="fun1">点击改变</button>
  </div>
</template>

<script>
import { reactive } from "vue";
export default {
  setup() {
    const name = "张三";
    const age = 13;
    const taobao = "淘宝";
    const obj1 = reactive([1, 2, 3, 4, 5, 6, 7]);
    const obj2 = reactive(
      {
        name,
        age,
        taobao,
        por: {
          a: {
            b: ["1", "2", "3"],
          },
        },
      },
    );

    const fun1 = () => {
      console.log(obj2);
      obj2.age = 23;
      obj2.name = "王五";
      
    };

    return { obj1, obj2, fun1 };
  },
};
</script>
<style scoped></style>

toRef 源数据的引用

toRef→真修改-不展示

ref→拷贝→修改→能展示

<template>
  <div>
    <h2>{{ obj.name }}</h2>
    <h2>{{ obj.age }}</h2>

    <button @click="fun1">点击改变</button>
  </div>
</template>

<script>
import { toRef } from "vue";
export default {
  setup() {
    const obj = { name: "马云", age: 50 };
    const res = toRef(obj,'name');

    const fun1 = () => {
      res.value.name= "马化腾";
      
      console.log(obj);
    };
    return { obj, fun1 };
  },
};
</script>
<style scoped></style>

toResf

val.valname.value

<template>
  <div>
    <h2>{{ name }}</h2>
    <h2>{{ age }}</h2>

    <h5>{{a}}</h5>
    <h5>{{b}}</h5>
    <h5>{{c}}</h5>
    <h5>{{d[0]}}</h5>
    <h5>{{e.f}}</h5>
    
    <button @click="fun1">点击改变</button>
  </div>
</template>

<script>
import { reactive, toRefs } from "vue";
export default {
  setup() {
    const obj = { name: "马云", age: 50 };
    const obj2 = reactive(obj);
    //const refs = toRefs(obj2); // toResf 应该接受一个响应式对象。
    
    const fun1 = () => {
      console.log(obj);
      console.log(obj2);
      //console.log(refs);
    };
    // ...toResf(obj2) // 扩展运算符

    const data = reactive({
        a: 12,
        b: 23,
        c: 'a',
        d: [1,2,3,4,5,6],
        e: {f:23}
    })


    return { ...toRefs(data),...toRefs(obj2),obj, fun1 };
  },
};
</script>
<style scoped></style>

computed 计算属性

vue3 中可以使用一个或者多个

<template>
  <div>
    <br />
    <h1>obj:{{ obj }}</h1>
    <br />
    <button @click="obj++">点击改变</button><br />

    <br />
    <h1>obj:{{ obj2 }}</h1>
    <br />
    <button @click="obj2++">点击改变</button><br />

    <br />
    <h1>obj:{{ obj3 }}</h1>
    <br />
    <button @click="obj3++">点击改变</button><br />

    <br />
    <h1>obj:{{ obj4 }}</h1>
    <br />
    <button @click="obj4++">点击改变</button><br />

    <br />
    <h1>obj5:{{ obj5.a.num}}</h1>
    <br />
    <button @click="obj5.a.num++">点击改变</button><br />
  </div>
</template>

<script>
import { reactive, ref, watch } from "vue";
export default {
  setup() {
    const value1 = 0;
    const obj = ref(value1);
    const obj2 = ref(0);
    const obj4 = ref(0);
    const obj3 = ref(0);
    // 监听obj变化
    watch(obj, (newVal, oldVal) => {
      console.log("新的值:" + newVal);
      console.log("旧的值:" + oldVal);
    });

    // 监听多个
    watch([obj2, obj3, obj4], (newVal, oldVal) => {
      console.log("新的值:" + newVal);
      console.log("旧的值:" + oldVal);
    },{immediate:true}); // 进入页面立即监听

    // 监听复杂对象
    const obj5 = reactive({
        a:{
            num:3
        }
    });
    watch(()=> obj5.a.num,(newVal,oldVal)=>{
      console.log("新的值:" + newVal);
      console.log("旧的值:" + oldVal);
    })

    return { obj, obj2, obj3, obj4,obj5 };
  },
};
</script>
<style scoped></style>


watch 侦听器

监听数据的变化

<template>
  <div>
    <br />
    <h1>obj:{{ obj }}</h1>
    <br />
    <button @click="obj++">点击改变</button><br />

    <br />
    <h1>obj:{{ obj2 }}</h1>
    <br />
    <button @click="obj2++">点击改变</button><br />

    <br />
    <h1>obj:{{ obj3 }}</h1>
    <br />
    <button @click="obj3++">点击改变</button><br />

    <br />
    <h1>obj:{{ obj4 }}</h1>
    <br />
    <button @click="obj4++">点击改变</button><br />

    <br />
    <h1>obj5:{{ obj5.a.num}}</h1>
    <br />
    <button @click="obj5.a.num++">点击改变</button><br />
  </div>
</template>

<script>
import { reactive, ref, watch } from "vue";
export default {
  setup() {
    const value1 = 0;
    const obj = ref(value1);
    const obj2 = ref(0);
    const obj4 = ref(0);
    const obj3 = ref(0);
    // 监听obj变化
    watch(obj, (newVal, oldVal) => {
      console.log("新的值:" + newVal);
      console.log("旧的值:" + oldVal);
    });

    // 监听多个
    watch([obj2, obj3, obj4], (newVal, oldVal) => {
      console.log("新的值:" + newVal);
      console.log("旧的值:" + oldVal);
    });

    // 监听复杂对象
    const obj5 = reactive({
        a:{
            num:3
        }
    });
    watch(()=> obj5.a.num,(newVal,oldVal)=>{
      console.log("新的值:" + newVal);
      console.log("旧的值:" + oldVal);
    })

    return { obj, obj2, obj3, obj4,obj5 };
  },
};
</script>
<style scoped></style>


watchEffect

<template>
  <div>
      <br>
      <h5>p1的值:{{p1}}</h5>
      <button @click="p1++">点击++</button>

  </div>
</template>
<script>
import { reactive, ref, watchEffect } from "vue";
export default {
  setup() {
    const p1 = ref(0);
    const p2 = reactive({ title: "标题", body: "身体" });
    const p3 = reactive({
      name: "张三",
      obj: {
        title: "电影",
        total: 200.23,
      },
    });

    const we = watchEffect(() => {
      console.log("第一次是否执行了?");
      console.log("p1:" + p1.value);
      console.log("p2:" + p3);
      console.log("p3:" + p2);
      const a = p1;
      console.log(a);
    });

    // 停止监听
    we(); 

    return { p1, p2, p3, we };
  },
};
</script>

shallowRef和shallowReactive

<template>
  <div>
    <br />
    <h5>p1的值:{{ p1 }}</h5>
    <button @click="p1++">点击++</button>

    <br />
    <h5>p5的值:{{ one }} | {{ tow.three }}</h5>
    <button @click="one++">第一层++</button>
    <button @click="tow.three++">第二层++</button>


    <br />
    <h5>p4的值:{{ p4 }} | {{ p4_a.taobao }}</h5>
    <button @click="p4++">处理基础数据类型++</button>
    <button @click="p4_a.taobao+= 'p' ">处理对象类型++</button>

  </div>
</template>
<script>
import { reactive, ref, shallowReactive, shallowRef, toRefs } from "vue";
export default {
  setup() {
    const p1 = ref(0);
    const p2 = reactive({ title: "标题", body: "身体" });
    const p3 = reactive({
      name: "张三",
      obj: {
        title: "电影",
        total: 200.23,
      },
    });

    const p4 = shallowRef(123); // 只处理基础数据类型
    const p4_a = shallowRef({ taobao: 123, baoba: "宝贝" }); // 不能处理对象
    const p5 = shallowReactive({ //只处理第一层
      one: 1,
      tow: {
        three: 23,
      },
    });
    
    return { p1, p2, p3, p4, p4_a, ...toRefs(p5) };
  },
};
</script>

组件之间的传值

方式一:

父组件

<CreateDialog ref="isOpenCreateDialog"/>
<script setup>
import CreateDialog from './CreateDialog.vue'

const isOpenCreateDialog = ref(null)

// 这个是父组件事件方法比如点击触发....
const addRow = () => {

  // changeDialog() 是子组件暴露的方法,也可以传递参数
  isOpenCreateDialog.value.changeDialog()
  
}
</script>

子组件

<script setup>

let isOpen = ref(false);

// 被调用的方法
const changeDialog = () => {
  isOpen.value = !isOpen.value;
}

// 暴露给父组件
defineExpose({
  changeDialog
})

</script>

vuex

npm install vue@next —save

import {useStore} from 'vuex'

创建数据仓库

其中state 就是数据仓库

import { createStore } from "vuex";

export default createStore({
    // 数据仓库
    state: {
        name: "马云",
        title: { name, body: "的身高", age: 23 },

    },
    // 同步调用 state
    mutations: {},
    // 异步调用 state
    actions: {},

    modules: {},
});

在组件中使用

<template>
  <div>vuex中 name 的值:{{res}}</div>
  <div>vuex中 title 的值:{{res2.name}} || {{res2.body}}</div>
  <div>toRefs = {{name}} || {{body}}</div>
</template>
<script>
import { computed, reactive, toRefs } from "vue";
import { useStore } from "vuex";
export default {
  setup() {
    const store = useStore();

    // 使用计算属性
    const res = computed(() => {
      console.log(store.state.name);
      console.log(store.state.title);
      return store.state.name;
    });

    //使用计算属性
     const res2 = computed(() => {
      console.log(store.state.name);
      console.log(store.state.title);
      return store.state.title;
    });

      const res3 = computed(() => {
      console.log(store.state.name);
      console.log(store.state.title);
      return reactive(store.state.title);
    });

    return {res,res2, ...toRefs(res3)}
  },
};
</script>

vuex异步调用, 同步中修改数据

index.js

import { createStore } from "vuex";

export default createStore({
    // 数据仓库
    state: {
        name: "马云",
        title: { name, body: "的身高", age: 23 },
    },
    // 同步调用 state
    mutations: {
        trigger(state) {
            console.log("被actions异步调用");
            state.name = "马化腾"; // 修改仓库数据,在同步中修改
        },
    },
    // 异步调用 state, 调用异步之前需要调用同步
    actions: {
        sub(store) {
            console.log("sub方法被调用了");
            store.commit("trigger");
        },
    },

    modules: {},
});

组件.vue

<template>
  <div>vuex中 name 的值:{{res}}</div>

  <div> <button @click="btn">异步调用</button></div>
</template>
<script>
import { computed } from "vue";
import { useStore } from "vuex";
export default {
  setup() {
    const store = useStore();

    // 使用计算属性
    const res = computed(() => {
      console.log(store.state.name);
      console.log(store.state.title);
      return store.state.name;
    });

    function btn (){
      store.dispatch("sub") //异步调用
    }

    return {res, btn}
  },
};
</script>

vuex 同步调用


    function btn (){
      //store.dispatch("sub"); //异步调用
      store.commit('trigger','雷军');
    }

生命周期函数

<template>
  <div>生命周期函数</div>
</template>
<script>
import { onBeforeMount, onMounted,onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted, onErrorCaptured } from "vue";
export default {
  setup() {
    onBeforeMount(() => {
      console.log("onBeforeMount,在挂载之前调用");
    });
    onMounted(()=>{
        console.log("onMounted,组件加载时调用,推荐请求api使用这个函数");
    });
    onBeforeUpdate(() => {
       console.log("onBeforeUpdate,数据更新时调用,类似侦听器"); 
    });
    onUpdated(()=>{
        console.log("onUpdated,数据更改导致虚拟DOM重新渲染,会调用这个函数");
    });
    onBeforeUnmount(()=>{
        console.log("onBeforeUnmount,在卸载组件实例之前调用");
    });
    onUnmounted(()=>{
        console.log("onUnmounted,在卸载组件实例之后调用");
    });
    onErrorCaptured(()=>{
        console.log("onErrorCaptured,当捕获一个来自子孙组件的错误时被调用");
    });

    return {};
  },
  created() {
    console.log("created,进入页面就执行");
  },
};
</script>

抽离封装

common.js


// 公用的数据或者方法
import { reactive } from "vue";

const public_a = () => {
    const res = reactive({
        target: "阿里巴巴",
        comply: "腾讯",
        age: 23,
    });
    return res;
};

export default public_a;

组件.vue

<template>
  <div>
    抽离封装
    <h5>{{ resa.age }}</h5>
    <h5>{{ resa.comply }}</h5>
    <h5>{{ resa.target }}</h5>

    <h5>{{ resa }}</h5>
  </div>
</template>
<script>
import { reactive } from "@vue/reactivity";
import public_a from "../config/common";

export default {
  setup() {
    const res = reactive({
      target: "阿里巴巴",
      comply: "腾讯",
      age: 23,
    });

    const resa = public_a();
    console.log(resa);
    return { res, resa };
  },
};
</script>