vue2.x学习笔记

116 阅读6分钟

theme: juejin

第一章Vue2.x实例

1.1 watch的相关使用

  1. watch介绍:

一般当响应数据的变化。需要在数据变化时执行异步或开销较大的操作时,这个方式是最有用的;

  1. watch的几种基本写法
   watch: {
    // 监视正常写法(基本数据类型)
    isHot: {
      handler(newValue, oldValue) {
        console.log("isHot被修改了", newValue, oldValue);
      },
      immediate: true,
    },
    // 引用数据类型写法
    Weather: {
      handler(newValue, oldValue) {
        console.log("isHot被修改了", newValue, oldValue);
      },
      immediate: true,
      deep: true,
    },
    // 监视引用数据类型中的某个属性
    "Weather.isHot": {
      handler(newValue, oldValue) {
        console.log("isHot被修改了", newValue, oldValue);
      },
      immediate: true,
    },
   // 监视简写(基本数据类型)
    isHot(newValue, oldValue) {
      console.log("isHot被修改了", newValue, oldValue);
    },
  },
  1. watch说明:

immediate:true|false 立即监视,当值为true时表示当组件挂载时就触发一次;

deep:true|false 深度监视,当值为true时可以监视到引用数据类型中的某个属性值变化;

1.2 computed的相关使用

  1. computed的介绍

当应用场景中如果我们所想要的数据不存在,但是这个数据可以通过目前已有的响应式数据计算出来,此时就考虑使用计算属性;

  1. computed的基本使用
computed: {
    // 下面是计算属性简写形式(只通过get得到数据)
     fristLast(){
        return this.frist + " " + this.last;
    },
    // 下面是计算属性正常形式(既可以通过get获取数据,也可以通过set修改数据)
    fristLast(){
      get: function () {
        return this.frist + " " + this.last;
      set: function (newVal) {
        var names = newVal.split(" ");
        this.frist = names[0];
        this.last = names[1];
      },
    },
  },

第二章Vue2.x指令指南

2.1 模板语法

  1. 插值

此处easy直接上代码

<!-- 下面两种的效果一样(强烈推荐 {{}} 写法)因为它里面写法更加灵活 -->
 <div  v-text="msg"></div>
 
  <div >{{ msg }}</div>
  
 <div >{{ number + 1 }}</div>
 
 <div >{{ ok ? 'YES' : 'NO' }}</div>

 <div >{{ message.split('').reverse().join('') }}</div>
 
  1. 指令

v-bind说明v-bind用来给标签绑定相关属性

   <el-button v-bind:type="type2">按钮</el-button>
   <!-- 简写形式 -->
   <el-button :type="type1">按钮</el-button>
   
   <!-- 也可以将动态绑定的属性名写成动态的 -->
   <el-button v-bind:[attributeName]="type2">按钮</el-button>
   <!-- 简写形式 -->
   <el-button :[attributeName]="type1">按钮</el-button>

v-bind相关修饰符

  • .prop修饰符用该修饰符后子组件的props将不能接收到该值;
  • .sync修饰符用该修饰符后相当于给子组件绑定了一个自定义事件,可以直接在子组件中修改父组件传递过来的数据;
  • .camel修饰符用该修饰符的作用是将父组件传递的aa-bb形式,修改为aaBb驼峰形式(父组件传递aa-bb时子组件props接受时应是aaBb
<!--父组件-->
<template>
  <div>
    <childVue
      :buttonValue="buttonValue"
      :buttonValue2.prop="buttonValue2"
      :button-value3.camel="buttonValue3"
      :buttonValue4.sync="buttonValue4"
    ></childVue>
  </div>
</template>

<!--子组件-->
<template>
  <div>
    <el-button type="">{{ buttonValue }}</el-button>
    <el-button type="">{{ buttonValue2 }}</el-button>
    <el-button type="">{{ buttonValue3 }}</el-button>
    <el-button
      type=""
      @click="$emit('update:buttonValue4', '子组件修改的值')"
      >{{ buttonValue4 }}</el-button
    >
  </div>
</template>
<script>
export default {
  name: "childVue",
  data() {
    return {};
  },
  props: ["buttonValue", "buttonValue2", "buttonValue3", "buttonValue4"],
};
</script>

<style lang="less" scoped></style>

v-on说明v-on 用来绑定事件;

    <el-button  v-on:click="msg = 'BBBBBBBB'">111</el-button>
    <!-- 简写形式 -->
    <el-button  @click="aa">111</el-button>
    
     <!-- 也可以将事件名写成动态的 -->
     <el-button  v-on:[hanlderName]="msg = 'BBBBBBBB'">111</el-button>
    <!-- 简写形式 -->
    <el-button  @[hanlderName]="aa">111</el-button>

v-on相关修饰符

<!-- 方法处理器 -->
<button v-on:click="doThis"></button>

<!-- 动态事件 -->
<button v-on:[event]="doThis"></button>

<!-- 内联语句 -->
<button v-on:click="doThat('hello', $event)"></button>

<!-- 停止冒泡 -->
<button @click.stop="doThis"></button>

<!-- 阻止默认行为 -->
<button @click.prevent="doThis"></button>

<!-- 阻止默认行为,没有表达式 -->
<form @submit.prevent></form>

<!--  串联修饰符 -->
<button @click.stop.prevent="doThis"></button>

<!-- 键修饰符,键别名 -->
<input @keyup.enter="onEnter">

<!-- 键修饰符,键代码 -->
<input @keyup.13="onEnter">

<!-- 点击回调只会触发一次 -->
<button v-on:click.once="doThis"></button>

<!-- 对象语法 (2.4.0+) -->
<button v-on="{ mousedown: doThis, mouseup: doThat }"></button>

2.2 样式绑定

  1. 绑定class

说明:绑定class分为对象绑定和数组绑定两种语法

  • 对象语法

写法一:

<!--例如 模板如下:-->
<div class="static" :class="{ active: isActive, 'text-danger': hasError }"></div>
<!--例如 数据如下:-->
data: {
  isActive: true,
  hasError: false
}
<!--模板渲染如下:-->
<div class="static active"></div>

写法二:

<!--例如 模板如下:-->
<div class="static" :class="classObj"></div>
<!--例如 数据如下:-->
data: {
  isActive: true,
  hasError: false
}
<!--通过计算属性计算classObj-->
  computed: {
    classObj() {
      return {
        active: this.isActive,
        "text-danger": this.hasError,
      };
    },
  },
<!--模板渲染如下:-->
<div class="static active"></div>
  • 数组语法
<!--例如 模板如下:-->
<div :class="[activeClass, errorClass]"></div>

<!--例如 数据如下:-->
data: {
 activeClass: 'active',
 errorClass: 'text-danger'
}

<!--模板渲染如下:-->
<div class="active text-danger"></div>

<!--如果须根据条件判断activeClass类是否生效,可用三元表达式-->
<div :class="[isActive ? activeClass : '', errorClass]"></div>
<!--除了用三元表达式以外还可用对象写法-->
<div :class="[{isActive:activeClass}, errorClass]"></div>
  1. 绑定style

说明:绑定style分为对象绑定和数组绑定两种语法

  • 对象语法
<!--例如 模板如下:-->
<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
<!--例如 数据如下:-->
data: {
  activeColor: 'red',
  fontSize: 30
}


<!--其实直接用一个对象数据更为优:-->
<!--例如 模板如下:-->
<div v-bind:style="styleObject"></div>
<!--例如 数据如下:-->
data: {
    styleObject:{
      activeColor: 'red',
      fontSize: 30
    }
}
<!--当然也可以用计算属性来实现喽~~~-->
  • 数组语法
<!--例如 模板如下:-->
div :style="[hasError, isActive]">asas</div>

<!--例如 数据如下:-->
 data() {
   return {
     isActive: { fontSize: "34px", width: "150px" },
     hasError: { backgroundColor: "red", height: "150px" },
   };
 },
  • 多重值

<div :style="{ border: ['1px', 'soild', 'red'] }"></div>

2.3 条件渲染

这里也比较简单就直接上代码了~~

v-if和v-show的区别::它两都是用来控制元素是否显示的指令,v-if所指令的元素显示——隐藏,元素会经过创建和销毁的过程。而v-show所指令的元素显示~隐藏是通过css中display:none属性进行隐藏。

  1. v-if
<div v-if="type === 'A'">
  A
</div>
<div v-else-if="type === 'B'">
  B
</div>
<div v-else-if="type === 'C'">
  C
</div>
<div v-else>
  Not A/B/C
</div>

  1. v-show
<div v-show="type === 'A'">
  A
</div>

2.4 列表渲染

  1. v-for遍历数组

说明:v-for可以用of代替in;也可以访问到本作用于之外的数据

<!--形式一:   v-for也可以该作用域之外的数据 -->
<ul>
  <li v-for="(item, index) in tableData" :key="index">
    {{ item.date + "===" + value }}
  </li>
</ul>

<!--形式二:   v-for也可以of代替in -->
<ul>
  <li v-for="(item, index) of tableData" :key="index">
    {{ item.date}}
  </li>
</ul>


//数据如下
 data() {
    return {
      tableData: [
        {
          date: "2016-05-02",
        },
        {
          date: "2016-05-04",
        },
        {
          date: "2016-05-01",
        },
        {
          date: "2016-05-03",
        },
      ],
      value: "时间选择器",
    };
  1. v-for遍历对象

说明:参数一:属性值,参数二:属性名;参数三:下标;

<!-- 模板如下: -->
<ul>
  <li v-for="(value, key, index) in items">
    {{ key + "======" + value + "======下标:" + index }}
  </li>
</ul>
 
<!-- 数据如下: -->

data(){
    return {
        items: {
        date: "2016-05-02",
        cnpo: "000000000001",
        state: "0",
      },
    }
}
  1. v-for维护状态

    说明:当数据发生变化时,vue会根据key值进行Dom节点的操作,所以在v-for中尽量使用值唯一的 key这里不建议使用index作为key

  2. v-for更新检测

    由于JavaScript的限制所以在Vue中不能对直接修改数组或对象的数据进行检测到,因此Vue提供了以下方法,在对数组和对象进行修改时会检测到;

  • push()

  • pop()

  • shift()

  • unshift()

  • splice()

  • sort()

  • reverse()

  • $set()

  • $delete()

    除了以上可以检测到数组/对象变化的方法外,如果使用检测不到的方法如下所示:

example1.items = example1.items.filter(
    function (item) 
        { 
            return item.message.match(/Foo/) 
        }
    )
  1. v-for过滤排序

有时在开发当中我们须对获取回来的数组进行整理(过滤或排序)后然后在进行展示;此时我们可以使用计算属性来完成该需求;

  computed: {
    tableData() {
      // 在这里计算出新的值
      if (this.value === "-1") {
        return this.tableDataCopy;
      } else {
        return this.tableDataCopy.filter((item) => item.state === this.value);
      }
    },
  },

v-for也可以嵌套使用,

<ul v-for="set in sets">
  <li v-for="n in even(set)">{{ n }}</li>
</ul>

data: {
  sets: [[ 1, 2, 3, 4, 5 ], [6, 7, 8, 9, 10]]
},
methods: {
  even: function (numbers) {
    return numbers.filter(function (number) {
      return number % 2 === 0
    })
  }
}

  1. v-for限制范围

v-for中也可以直接遍历一个整数;

<ul>
  <li v-for="n in 10">{{ n }}</li>
</ul>
  1. v-for在模板上使用
  2. v-for在组件上使用
  3. v-for注意事项

注意: 不建议将v-forv-if同时在同一节点使用,因为v-for的优先级高于v-if,因此它会在遍历的每个节点上都会有v-if指令存在,所以可以将v-if用于v-for外层节点元素上;

2.5 事件绑定

  1. 事件监听

可以使用v-on来监听DOM事件的触发事件;

 <el-button type="" v-on:click="complain">投诉</el-button>
 <!-- 简写形式如下 -->
 <el-button type="" @:click="complain">投诉</el-button>
 
 methods:{
     complain(){
     }
  }
  1. 事件修饰符
<!-- 阻止单击事件继续传播 -->
<a v-on:click.stop="doThis"></a>

<!-- 提交事件不再重载页面 -->
<form v-on:submit.prevent="onSubmit"></form>

<!-- 修饰符可以串联 -->
<a v-on:click.stop.prevent="doThat"></a>

<!-- 只有修饰符 -->
<form v-on:submit.prevent></form>

<!-- 添加事件监听器时使用事件捕获模式 -->
<!-- 即内部元素触发的事件先在此处理,然后才交由内部元素进行处理 -->
<div v-on:click.capture="doThis">...</div>

<!-- 只当在 event.target 是当前元素自身时触发处理函数 -->
<!-- 即事件不是从内部元素触发的 -->
<div v-on:click.self="doThat">...</div>

<!-- 2.1.4 新增,点击事件将只会触发一次 -->
<a v-on:click.once="doThis"></a>

<!-- 2.3.0 新增,滚动事件的默认行为 (即滚动行为) 将会立即触发 -->
<!-- 而不会等待 `onScroll` 完成  -->
<!-- 这其中包含 `event.preventDefault()` 的情况 -->
<div v-on:scroll.passive="onScroll">...</div>
  1. 按键修饰符
<!-- 只有在 `key` 是 `Enter` 时调用 `vm.submit()` -->
<input v-on:keyup.enter="submit">

<div @:scroll.passive="onScroll">...</div>

//可以通过全局 `config.keyCodes` 对象自定义按键修饰符别名
// 可以使用 `v-on:keyup.f1`
Vue.config.keyCodes.f1 = 112
  • .enter(回车键)
  • .tab(Tab键)
  • .delete (捕获“删除”和“退格”键)
  • .esc(Esc键)
  • .space(空格键)
  • .up(上箭头键)
  • .down(下箭头键)
  • .left(左箭头键)
  • .right(右箭头键)
  1. 系统修饰符
<!-- Alt + C -->
<input v-on:keyup.alt.67="clear">

<!-- Ctrl + Click -->
<div v-on:click.ctrl="doSomething">Do something</div>

2.6 表单绑定

  1. 绑定值

可以用v-model对表单数据进行绑定,当表单数据发生改变时,所绑定的数据也会被修改;它相当于v-bild+ @change的结合使用

<input v-model="message" placeholder="edit me">
                ||
<input :value"message" @change='changeHanlder($event)' placeholder="edit me">

//定义数据
data() {
    return {
            message:'请输入值'
        }
    }
    
//修改的方法
methods: {
    changeHanlder(event){
        this.message = event
    }
}
  1. 修饰符
  • .number将用户输入的值转化为number类型数据;
  • .lazy只有当用户在输入框输入完数据后(光标离开时)触发事件;
  • .trim自动去除输入文本前后的空格;
 <el-input
    v-model.number="formLabelAlign.content"
  ></el-input>

第三章Vue2.x生命周期

每个 Vue 实例在被创建时都要经过一系列的初始化过程——例如,需要设置数据监听、编译模板、将实例挂载到 DOM 并在数据变化时更新 DOM 等。同时在这个过程中也会运行一些叫做生命周期钩子的函数,这给了用户在不同阶段添加自己的代码的机会

3.1 beforCreaed

详情说明:此时实例初始化完成,可以打印出this并在打印的this对象中可以看到实例上的相关数据和方法。但是不能直接打印出this.xxx

3.2 created

详情说明: 此时可以直接打印出实例this身上的相关属性和方法。数据的观测,属性和方法的运算等,但是DOM的挂载阶段还没开始。$el属性尚不可用。

3.3 beforeMount

详细说明: 在挂载开始前被调用,相关的render函数首次被调用。(注意:此时如果有子组件,子组件开始执行beforCreaed,created,beforeMount,mounted四个阶段)

3.4 mounted

详细说明:实例被挂载后调用,此时可以拿到真实DOM了。(注意:mounted 不会保证此阶段所有的子组件也都一起被挂载。如果你希望等待视图更新完的话可以在该钩子函数里使用this.$nextTick)。

3.5 beforeUpdate

详细说明:当数据发生变化时会触发该钩子函数,此阶段数据已经被修改了,但是视图还是之前的视图。(注意:如果有子组件的话在此阶段相关的子组件会经历beforeUpdateupdated阶段)

3.6 updated

详细说明: 此时视图已被渲染为最新视图。

3.7 beforeDestroy

详细说明: 此时还可以拿到相关的属性,方法以及真实DOM元素。组件还没销毁。(注意:如果有子组件的话在此阶段相关的子组件会经历beforeDestroy,destroyed

3.8 destroyed

详细说明:组件被销毁后该钩子被调用。

3.9 activated

详细说明:被 keep-alive 缓存的组件激活时调用。

3.10 deactivated

详细说明:被 keep-alive 缓存的组件停用时调用。

3.11 errorCaptured

详细说明:用来捕获一个来自子孙组件的错误时被调用。此钩子会收到三个参数:错误对象、发生错误的组件实例以及一个包含错误来源信息的字符串。此钩子可以返回false以阻止该错误继续向上传播。

3.12生命周期钩子示意图

fd8f100c078570cdcf7dfe0b7e28c5d2.png

第四章Vue2.x过滤器

4.1 过滤器的基本使用

说明混入 (mixin) 提供了一种非常灵活的方式,来分发 Vue 组件中的可复用功能。一个混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被“混合”进入该组件本身的选项。

//创建一个mixin.js
// 定义一个混入对象
let myMixin = {
  created() {
    console.log('我是myMixin的created');
  },
  data() {
    return {
      message: '我是minix数据'
    }
  },
  methods: {
    hello() {
      return 'hello from myMixin'

    }
  },
}
export default myMixin
//创建一个vue文件
<template>
  <div id="demo">
    <button v-on:click="show = !show">{{ message }}</button>
      <div>{{ hello() }}</div>
  </div>
</template>
<script>
import myMixin from "./mixin.js";
export default {
  mixins: [myMixin],
  name: "index",
  data() {
    return {
      show: true,
      message: "组件数据",
    };
  },
  created() {
    console.log("我是组件中的created");
  },
  mounted() {
    console.log("tttttt", this.message, this.hello());
  },
  methods: {
    hello() {
      return "hello from 组件";
    },
  },
};
</script>

<style lang="less" scoped>

</style>

第五章Vue2.x组件的使用

5.1插槽的基本使用

<!--在子组件中声明一个插槽<slot></slot>-->
<template>
  <div>
    <el-button type="">
      <slot></slot>
    </el-button>
  </div>
</template>

<!-- 在父组件中将所要填充的内容填充到子组件中 -->

<childVue>
  <template>插槽按钮</template>
</childVue>

5.2具名插槽

说明:具名插槽顾名思义就是给插槽起一个名字

<template>
<!--子组件中-->
  <div class="container">
    <header>
      <slot name="header"></slot>
      <!-- 我们希望把页头放这里 -->
    </header>
    <main>
      <!-- 我们希望把主要内容放这里 -->
      <slot name="main"></slot>
    </main>
    <footer>
      <!-- 我们希望把页脚放这里 -->
      <slot name="footer"></slot>
    </footer>
  </div>
</template>

<!--父组件中-->
 <childVue>
  <template v-slot:footer>
    <p>底部</p>
  </template>
  <template v-slot:main>
    <p>内容区</p>
  </template>
  <template v-slot:header>
    <p>顶部</p>
  </template>
</childVue>
    

5.3作用域插槽

说明:作用域插槽就是根据子组件的数据对填充的内容进行渲染。

<!--子组件中-->
 <template>
  <div class="container">
    <main>
      <!-- 我们希望把主要内容放这里 -->
      <slot :hobby="hobby"></slot>
    </main>
  </div>
</template>
<script>
export default {
  name: "childVue",
  data() {
    return {
      hobby: ["打游戏", "睡大觉", "吃大餐"],
    };
  },
};
</script>

<!--父组件中-->
<childVue>
  <template v-slot:footer>
    <p>底部</p>
  </template>
  <template slot-scope="{ hobby }">
    <ul>
      <li v-for="(h, index) in hobby" :key="index">{{ h }}</li>
    </ul>
  </template>
  <template v-slot:header>
    <p>顶部</p>
  </template>
</childVue>
    

5.4 作用域 + 具名插槽

// 父组件
<template>
  <div class="">
    <HelloWorld>
      <template v-slot:a="value">
        <h2>{{ name }}</h2> // 这个是具名插槽
         <!--  value 是子组件传过来的数据 -->
        <h2>{{ value.value }}</h2> // 这个是作用域插槽
      </template>
    </HelloWorld>
  </div>
</template>
<script>
import HelloWorld from "../components/HelloWorld.vue";
export default {
  data() {
    return {
      name: "具名插槽 slot插槽传数据 父传子",
    };
  },
  components: { HelloWorld },
};
</script>
 
 
// 子组件
<template>
  <div>
    <slot name="a" :value="value"></slot>
  </div>
</template>
<script>
export default {
  data() {
    return {
      value: "我是子组件数据 作用域插槽子传父 s-z-h",
    };
  },
  methods: {},
};
</script>

第六章Vue中组件间通信

6.1 props(父子组件相互通信)

说明1:如果通过props传递的是一个数据的话,就是父组件-->子组件,但是props传递的数据是不能在子组件中直接修改的。(如果修改的话须借助.sync修饰符)

<!--父组件中-->
<childVue :message.sync="message"></childVue>

<!--子组件中-->
<el-button type="" @click="$emit('update:message', '修改props数据')">{{message}}</el-button>

说明2如果想要子组件-->父组件传递数据的话那就通过props向子组件传递一个函数用来获取子组件的数据。(通过此方法可以直接在父组件修改该属性)。

6.2 v-model(父子之间通信)

说明: v-model适用于子组件为表单类元素时的父子组件通讯。

<!--父组件中-->
1.    
  <template>
1.  <div class="">
1.    <HelloWorld v-model:obj="value"></HelloWorld>
1.    {{ value }}
1.  </div>
1.

<!--子组件中-->
<template>
<input :value="value" @input="handlerChange" />
</template>
<script>
export default {
props: ["value"],
methods: {
  handlerChange(e) {
     // 一定要是 input 事件
    this.$emit("input", e.target.value);
  },
},
};

6.3 ref(子-->父传递数据)

说明:可以通过在组件中添加ref属性通过$refs获取到真实DOM来获取到该 组件身上的数据或调用其方法。

<HelloWorld ref="child"></HelloWorld>

const child = this.$refs.child;
console.log(child.str); // 获取子组件的数据
child.fn("调用了子组件的方法");//调用了子组件的方法

6.4 $emit/v-on(子--->父传递数据)

说明: 在父组件给子组件绑定一个事件,适用于当子组件在某个特定的时期需要触发父组件的事件,并要给子组件传值。

6.5 $attrs(父--->孙传递数据) / $linteners(孙--->父传递数据)

$attrs说明: 包含父作用域里除 class 和 style 除外的非 props 属性集合。通过 this.attrs获取父作用域中所有符合条件的属性集合,然后还要继续传给子组件内部的其他组件,就可以通过vbind="attrs 获取父作用域中所有符合条件的属性集合,然后还要继续传给子组件内部的其他组件,就可以通过 v-bind="attrs"。

$linteners说明:包含父作用域里 .native 除外的监听事件集合。如果还要继续传给子组件内部的其他组件,就可以通过 v-on="$linteners"

6.6 $children / $parent

$children说明:用于获取子组件中的属性或方法。

1.  mounted() {
1.  this.$children[0].fn(); // 调用第一个子组件的方法
1.  console.log(this.$children[0].name); // 获取第一个子组件中的属性
1.  },

$parent说明: 用于获取父组件中的属性或方法。

  mounted() {
  this.$parent.fn(); // 调用父组件的方法
  console.log(this.$parent.name); // 获取父组件中的属性
  },

6.7 provide / inject 依赖注入(祖孙之间通信传值)

说明:可以将本组件中的属性和方法注入到孙组件中(该方法注入的数据不是响应式的数据)

<!--父组件-->
 provide() {
 return {
  name: this.val, // data 的数据
  someMethod: this.someMethod, // methods 中的方法
  };
 },
 
<!--孙组件-->
  inject: ["name", "someMethod"],
  mounted() {
  console.log(this.name);
  this.someMethod();
  },

6.8 EventBus全局事件总线(任意组件通讯)

说明:EventBus 是中央事件总线,不管是父子组件,兄弟组件,跨层级组件等都可以完成通信

// 找到main.js 加入一下代码  公共的$bus
Vue.prototype.$bus = new Vue()

//在接受值的组件中绑定一个方法
  mounted() {
  this.$bus.$on("fn", (value) => {
  console.log(value);
  });
  },
  
//在发送值的组件中触发该方法
  methods: {
    fn(val) {
      if (val) {
        this.value = val;
      }
      console.log("ttttt", this.value);
      return this.value;
    },
  },

6.9 VueX通讯

说明: 可以定义共享的数据源,在哪里都可以访问 安装配置 使用即可。

使用详情--->《Vuex和Pinia的基本使用》

6.10 具名插槽+作用域插槽 slot

说明:具体使用可见5.3节文章内容。

6.11 $root

说明:$root 可以拿到 App.vue 里的数据和方法。

// HelloWorld 子组件添加数据
<template>
  <div></div>
</template>
<script>
export default {
  data() {
    return {};
  },
  mounted() {
    // 写入根组件的数据
    this.$root.foo = 2;
  },
  methods: {},
};
</script>
 
// Home 父组件访问数据
<template>
  <div class="">
    <HelloWorld></HelloWorld>
  </div>
</template>
<script>
import HelloWorld from "../components/HelloWorld.vue";
export default {
    data() {
        return {};
    },
    mounted() {
        // 获取根组件的数据
        console.log(this.$root.foo);
    },
    components: { HelloWorld }
};
</script>

6.12 pubsub(任意组件间通讯)

pubsub说明: 该功能是一个第三方插件。

使用说明:

  • 安装模板
npm install --save pubsub-js
  • 引入模块
  import PubSub from 'pubsub-js'
  • 订阅消息
PubSub.subscribe('消息名', function('消息名', [data]){})
  • 发布消息
PubSub.publish('消息名', [data])
  • 取消订阅
PubSub.unsubscribe('消息名')

第七章其它API补充

6.1 extends

说明:这和mixins类似,主要用于复用其它组件。

import childVue from "./childVue.vue";

export default {
  ·····
  extends: childVue,

};

6.2 $nextTick

说明:在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。

// 修改数据
this.msg = 'Hello' 
// DOM 还没有更新 
this.nextTick(function () {   // DOM 更新了
})

6.3 $set/$delete

说明:由于Vue2.x对于引用型数据后期用户直接添加属性和删除新添加的属性,它是无法检测到响应式的,因此它提供了这两个API,通过这两个API修改的引用型数据依然是响应式的。

// 修改&&删除数组

this.$set(this.array, index, newValue);
this.$delete(this.array, index);

// 修改&&删除对象
this.$set(this.obj, 'show', false);
this.$delete(this.obj, 'show');