Vue-基础

指令

重要指令

  1. v-for
  2. v-if v-else-if v-else
  3. v-bind
  4. v-on
  5. v-model

一般指令

  1. v-show
  2. v-text v-html

不重要的指令

  1. v-once
  2. v-cloak
  3. v-pre

生命周期

生命周期中包含了四个过程 创建 挂载 更新 销毁

  1. beforeCreate
  2. created
  3. beforeMount
  4. mounted
  5. beforeUpdate
  6. updated
  7. beforeDestroy
  8. destroyed

配置

计算属性



new Vue ({
  data: {
    msg: "hello world",
    stu: [
      {
        name: '张三',
        age: 18,
        sex: '男'
      }, {
        name: '李四',
        age: 20,
        sex: '女'
      }
    ]
  },
  computed: {
    demo () {
      return 1
    },
    // demo: 1
    reverseMsg () {
      return this.msg.split('').reverse().join('')
    },
    boys () {
      return this.stu.filter(stu => stu.sex === '男')
    }
  }
})

监听

new Vue({
data: {
msg: ''
},
watch: {
msg (newMsg, oldMsg) {

},

msg: {
  handler (newMsg, oldMsg) {

  },
  deep: true,
  immediate: true
}

}
})

methods

绑定的事件,以及页面上需要用到的函数,我们可以加载methods。如果调用则使用this.方法名()

组件

组件注册

需要组件配置对象(就是一个普通对象)

组件配置对象

  const 对象名(组件名) = {
    // template中有且只能有一个根节点
    template: `
      
`, // 函数返回值的形式 data () { return { // 组件中的data默认只能被当前组件获取 msg: "" } } }

全局注册

在所有的组件中都可以直接使用

Vue.component('组件名', 组件配置对象)

const com1 = {
  name: 'com1'
}
const com2 = {
  name: 'com2'
}
const com3 = {
  name: 'com3'
}

const com4 = {
  name: 'com4'
}

const components = [com1, com2, com3, com4]

components.forEach(component => Vue.component(component.name, component))

局部注册

const BedRoom = {
  template: `
    
卧室
` } const House = { template: `
`, components: { // 组件名: 组件配置对象 BedRoom: BedRoom } }

组件关系

Vue只有两种关系, 父子组件 非父子组件

组件通信

  1. 父子通信

当我们需要把父组件中的数据传递给子组件时,使用父子通信

父组件

const Parent = {
  template: `
    
`, data () { return { msg: "这是父组件中的数据" } } }

子组件

const Child = {
  template: `
    
{{m}}
`, // 设置prop接收 props: ['m'] }
  1. 子父通信

当我们要把子组件中的数据,传递给父组件时,使用子父通信

父组件

const Parent = {
  template: `
    
`, data () { return { msg: '父组件中的数据' } }, methods: { getMsg (msg) { this.msg = msg } } }

子组件

const Child = {
  template: `
    
{{msg}}
`, props: ['msg'], methods: { changeMsg () { // this.msg = "新的内容" // 错误的 不要在子组件中直接修改父组件中传来的数据 // 正确的 this.$emit('send:msg', '子组件发过去的数据') } } }

在组件标签上看到属性,那么表示对应的父组件给子组件传值,如果我们在组件标签上看到@xxx="函数" 表示父组件在监听子组件的自定义事件





  1. 非父子通信

利用的是自定义事件,因为自定义事件的监听和触发必须得是同一个this,所以我们需要一个公共的vue实例,称其为bus

bus

const bus = new Vue()

组件1

const com1 = {
  template: `
    
`, methods: { changemsg () { bus.$emit('changeMsg', '数据') } } }

组件2

const com2 = {
  template: `
    
{{msg}}
`, data () { return { msg: '消息' } }, created () { bus.$on('changeMsg', (msg) => { this.msg = msg }) } }

插槽

普通插槽

const com = {
  template: `
    
其他内容
` }
自定义内容

具名插槽

默认的slot有一个名字为default

const com = {
  template: `
    
其他内容
` }

作用域插槽

给用户留一些需要的数据

const com = {
  template: `
    
其他内容
` }

你可能感兴趣的:(Vue-基础)