vue2和vue3的一些技术点复习

一、vue3  

1、父子组件传值

子组件

<template>
    <div class="base-input flex align-center">
		<div class="base-name" v-if="props.blockName">{{ props.blockName }}</div>
		<el-input placeholder="请输入" v-model="changeValue"></el-input>
		<input placeholder="普通input传值" v-model="nativeValue" @input="changeNativeValue"/>
    </div>
</template>
<script lang='ts' setup>
import { computed, toRefs } from 'vue'
const props = defineProps({
	blockName: {
		type: String,
		default: ''
	},
	value: {
		type: String,
		default: ''
	},
	nativeValue: {
		type: String,
		default: ''
	},
})
const {nativeValue} = toRefs(props);
const emits = defineEmits(['update:value','update:nativeValue'])
// 通过重写计算属性的set和get方法,将计算属性的结果绑定在输入框的model中
const changeValue = computed({
	get: () => props.value,
	set: (val) => {
		emits('update:value', val)
	}
});
const changeNativeValue = (e) => {
	console.log(e, e.target, e.target.value)
	emits('update:nativeValue', e.target.value)
}
</script>
  

父组件

<template>
    <div class="page">
        <BaseInput blockName="姓名" v-model:value="elValue" v-model:nativeValue="nativeValue"/>
        <div @click="getInputValue">获取两个输入框的值</div>
    </div>
</template>
<script setup>
import { ref } from 'vue'
import BaseInput from '@/components/child.vue';

const elValue = ref('');
const nativeValue = ref('');
const getInputValue = () => {
    console.log(elValue.value, nativeValue.value, 'input value')
}
</script>
2、插槽使用

使用插槽

<template>
    <div class="page">
        <child>
            <template #header="{ text, count }">
                <div>{{ text }}{{ count }}</div>
            </template>
            <p>main 部分内容</p>
            <template #tips>
                <div></div>
                {{message}}
            </template>
            <template #footer>
                <div>我是底部</div>
            </template>
        </child>
    </div>
</template>
<script setup>
import { ref } from 'vue'
import child from '@/components/child.vue';

const message = ref('该提示做个展示');

</script>

插槽页面

<template>
	<div class="child-box">
	  <p>我是子组件</p>
	  <slot name="header" :text="`默认值:`" :count="1"></slot>
	  <!-- 默认 -->
	  <slot></slot>
	  <slot name="tips"></slot>
	  <slot name="footer"></slot>
	</div>
</template>
  
3、hooks
  • vue3 中的 hooks 函数相当于 vue2 里面的 mixin 混入,不同在于 hooks 是函数且显式引入。
  • vue3 中的 hooks 函数可以提高代码的复用性,能够在不同的组件当中都利用 hooks 函数。
  • hooks 函数可以与 mixin 连用,但是不建议。

建立usePublic.js

import { ref } from 'vue'

export default function() { // 导出一个默认方法

    // 创建一个对象,保存值
    const message = ref("默认消息")

    // 创建一个方法,获取可视化界面的值
    const getMessage = () => {
        message.value = "变化消息";
    }

    return { message, getMessage } // 方法返回值
}

使用hooks

<template>
    <div class="page">
        <div @click="getMessage">切换</div>
        <div>{{ message }}</div>
    </div>
</template>
<script setup>
import usePublic from '@/hooks/usePublic.js';

const {message, getMessage} = usePublic();

</script>
4、vuex

安装依赖

npm install vuex --save

新建store文件->index.js,进行如下配置,在main.js中进行引入

import { createStore } from 'vuex'

// 创建一个新的 store 实例
const store = createStore({
    state() {
        return {
            count: 0
        }
    },
    mutations: {
        increment(state) {
            state.count++
        }
    }
})
export default store;

在app.js中

 在页面中使用

<template>
    <div class="page">
        <div>{{ count }}</div>
        <div @click="change">触发更新</div>
    </div>
</template>
  
<script setup>
import { useStore } from 'vuex'
import { computed } from 'vue'

const store = useStore();
const change = () => {
    console.log('触发更新')
    store.commit('increment')
}
const count = computed(() => store.state.count);
console.log(count,'test')
</script>

5、生命周期vue2和vue3的对比
vue2           ------->      vue3
 
beforeCreate   -------->      setup(()=>{})
created        -------->      setup(()=>{})
beforeMount    -------->      onBeforeMount(()=>{})
mounted        -------->      onMounted(()=>{})
beforeUpdate   -------->      onBeforeUpdate(()=>{})
updated        -------->      onUpdated(()=>{})
beforeDestroy  -------->      onBeforeUnmount(()=>{})
destroyed      -------->      onUnmounted(()=>{})
activated      -------->      onActivated(()=>{})
deactivated    -------->      onDeactivated(()=>{})
errorCaptured  -------->      onErrorCaptured(()=>{})

二、vue2

1、vue2对已有组件二次封装,例如fes2 input 组件(文档链接)

子组件

<template>
    <div class="keyboard-page">
        <wb-input
            :id="keyBoardId"
            :placeholder="placeholder" 
            :type="type" 
            :disabled ='disabled'
            v-model="inValue"
            :maxlength="maxlength"
            :autocomplete="autocomplete"
            @on-focus="$emit('onKeyFocus')"
            @on-change="$emit('onKeyChange')"
            @on-enter="$emit('enterQuery')"
            :slotType="slotType"
            :slotValue="slotValue"
        >
            <template v-if="slotType === 'TEXT' ">
                <span :slot="slotLocation">{{slotValue}}</span>
            </template>
        </wb-input>
    </div>
</template>
<script>
export default {
    name: 'input',
    model: {
        prop: "modelValue",
        event: "returnModel",
    },
    props: {
        placeholder: {
            type: String,
            default: '请输入' 
        },
        type: {
            type: String,
            default: 'text'
        },
        disabled: {
            type: Boolean,
            default: false
        },
        modelValue: String | Array | Object | Boolean | Number,
        keyBoardId: {
            type: String,
            default: '',
        },
        
        maxlength: {
            type: Number
        },
        autocomplete: {
            type: String,
            default: '',
        },
        isSlot: {
            type: Boolean,
            default: false
        },
        slotLocation: {
            type: String,
            default: 'prepend',
        },
        slotType: {
            type: String,
            default: '',
        },
        slotValue: String | Array | Object | Boolean | Number,
    },
    computed: {
        inValue: {
            get: function () {
                return this.modelValue;
            },
            set: function (newValue) {
                this.$emit("returnModel", newValue);
                return newValue;
            },
        },
    },
}
</script>

父组件引入

<template>
    <div class="page">
        <keyBoardInput 
            :keyBoardId="'productSearchInfo'"
            @onKeyFocus="searchInputFocus"
            @onKeyChange="fuzzyMatching"
            @enterQuery="search"
            v-model="queryData.searchInfo"
            autocomplete="on" 
            placeholder="请输入查询条件(支持产品编码/产品名称检索)"
        ></keyBoardInput>
    </div>
</template>
<script>
import keyBoardInput from "@/components/keyboard.vue";

export default {
    name: 'About',
    components: {
        keyBoardInput,
    },
    data() {
        return {
            queryData: {
                searchInfo: ''
            } 
        };
    },
    methods: {
        search() {
            console.log('enter 查询')
        },
        searchInputFocus() {
            console.log('获取焦点')
        },
        fuzzyMatching() {
            console.log('change')
        },
    },
};
</script>
2、插槽使用 slot、v-slot、slot-scope

参考此链接

3、mixin

mixins.js

let mixin = {
  created() {
    console.log("我是mixin里面的created!")
  },
  methods: {
    hello() {
      console.log("hello from mixin!")
    }
  }
}
 
export default mixin

页面引入

<template>
  <div class="home">
    <span>This is a Home page</span>
  </div>
</template>
 
<script>
import myMixins from "../mixins";
export default {
  name: 'Home',
  mixins: [myMixins],
  mounted(){         
    this.hello()     //在该组件中并没用定义hello方法,使用的是混入中的hello
  }
}
</script>

选项合并:当组件和混入对象含有同名选项时,这些选项将以恰当的方式进行“合并”。数据对象在内部会进行递归合并,并在发生冲突时以mixin数据优先。

4、vuex

参考此链接

5、生命周期

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值