混入mixin
- 对相同的js代码进行抽取,公共代码抽取、共享
- 使用方法
- export default xxMixin = {//在js文件里
- data(){
- return{
- obj: '123'
- }
- },
- created(){
-
- }
- }
- 组件中使用混入
- import { demoMixin } from './xxMixin';
- export default {
- mounted(){},// 同级目录
- mixin: [xxMixin],//一般是数组,
- }
-
- mixin里,data数据冲突会保留组件里的
- mixin里,钩子函数重复是合并的
- 全局混入
- 在main.js里
- const app = createApp(App);
- app.mixin({
- data(){
- return{}
- }
- })
Vue3 composition API
- Vue2 option API 代码非常碎片化,难以阅读,所以有composition API
- setup函数有参数props,和context上下文
- setup函数无法使用this.
- props:[‘abc’],
- setup( props,context ){
-
- }
- //第二种写法
- setup( props,{ attr,slots,emit } ){
-
- }
-
context有三个属性
- attrs: 所有非prop的attribute
- slots: 父组件传递过来的插槽
- emit: 用于向父组件发送事件
-
setup的返回值相当于定义data setup( props, { attrs,slots,emit }) { const addBtn = () => {} return{ time: xx, addBtn, } }
-
reactive 响应式API
- 导入import { reactive } from 'vue';
- 在setup里使用
- const state = reactive({
- counter: 100
- })
-
- return{
- state,
- }
- 在模板里使用
- {{ state.counter }}
- ref API 可响应式的引用(依旧先导入)
- const counter = ref(100)
- counter.value++;
- 在模板中
- {{ counter }} //自动解包
- readonly API 只读 const info = readonly( info2 )