Vue学习笔记

2019/3/6 Vue

TIPS

前端Vue学习笔记

# 初始化Vue

//vue2.x写法
new Vue({
  router,
  render: h => h(App)
}).$mount("#app");

//或者
new Vue({
  el: '#app',
  router,
  render: h => h(App)
});

//也可以先得到Virtual DOM, 再挂载
var component = new MyComponent().$mount()
document.getElementById('app').appendChild(component.$el)

//vue1.x写法
new Vue({
  el: '#app',
  components: { App }
});

// 也可以用 template 模板字符串, 模板将会替换挂载的元素
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# 常用语法

  • v-bind:href="" 缩写: :href=""

  • v-on:click="" 缩写: @click=""

  • v-html innerHTML (不能直接解析成html标签)

  • v-text innerText

  • 动态样式

    • v-bind:class="" :class=""
    • 可以传对象: key/value -->bool, 可以传数组, 放入类名字符串, 也可以传变量数据
    • :style="" 用法相同
  • v-if 值为true显示, false隐藏, 元素会被移除, 调用不频繁可使用

  • v-else if为假的时候执行, 必须两者连续使用, 不能有第三者 ( v-else-if 是一样的)

  • v-show 值为true显示, false隐藏, 元素不会被移除, 调用频繁可用 (原理是切换 display)

  • 列表渲染 v-for="item in newsList" :key="item.id"

    v-for 既可以循环数组也可以循环对象 (对象包含key, value, index)

WARNING

直接利用索引值设置一个项时, 系统不会检测到数组的变化, 不会渲染新的页面, 但是利用数组的变异方法可以引发视图更新, 如push, pop等

Vue.set(vm.items, indexOfItem, newValue) 利用索引值也可使数组视图更新 (vm.$set(vm.items, indexOfItem, newValue)

Vue 不能检测对象属性的添加或删除, 同样需要Vue.set来修改或者像数组一样直接修改引用

v-for 的优先级高于 v-if, 因此要把 v-if 写在 v-for 的外面

input里面使用 v-model 实现数据双向绑定

# 组件

  1. 全局组件

    Vue.component('courseList',{
      template: `<div>hello world!</div>`
    })
    
    1
    2
    3
  2. 局部组件

    定义在vue实例里面, 也可以拿出来, 如果局部组件和全局组件名字相同, 则优先使用局部组件

  3. 动态组件

    <component :is="componentId"></component>
    // is里面是什么就显示什么
    
    1
    2

keep-alive可以保持组件切换的时候输入的数据不被清空, 实现缓存

组件传值: props, emit

# 插槽

<slot name="name"></slot>
// 具名插槽, slot="name"规定插入的dom元素在哪个地方
// 作用域插槽
<template slot-scope="two">
1
2
3
4

# 模版字符串

ES6中提供了模版字符串, 用 ``` (反引号)标识, 用 ${ } 将变量括起来

const person = {name: 'xxx', age: 20}
const str = `He is <b>${person.name}</b>and we wish to know his${person.age}.that is all`
1
2
最近更新: 2023年03月21日 14:47:21