9.VUE组件定义、事件绑定与脚手架-CLI

61 阅读1分钟

一、组件 VueComponent

<div id="root">
    <hi></hi>  // 组件实例对象hi
    <hello></hello>  // 组件实例对象hello
</div>
<script>
    //  定义hi组件
    // 创建hi -> VueComponent 构造函数
    const hi = Vue.extend({
        name: 'hi',  // 组件名
        template: '...',
        data() {...}
    })
    //  定义hello组件
    // 创建hello -> VueComponent 构造函数
    const hello = Vue.extend({
        name: 'hello',
        template: '...',
        data() {...}
    })

    //  创建vm实例
    new Vue({
        el: '#root',
        components: {hi, hello}
    })
<script/>

二、事件绑定

原生事件类型绑定:

<Student @click.native="show"/>

自定义事件绑定:(通过父组件给子组件绑定一个“自定义事件”实现:“子给父”传递数据)

方式一:(使用@或v-on)

// 父级
// Student组件实例对象绑定自定义事件@student
<Student @student="getStudentName"/>
...
methods: {
    getStudentName(name){
        console.log("事件被触发了" + "接收到的参数为" + name)
    },
}

方式二:(使用ref,控制方便)

// 父级
<Student ref="student"/>
...
mounted() {
    // 当事件发生时执行回调函数
    this.$refs.student.$on('student', this.getStudentName)  //绑定自定义事件
        // 或
    this.$refs.student.$once('student', this.getStudentName)  //绑定自定义事件(一次性)
}

自定义事件触发:

// 子级
<template>
    <button @click="sendStudentlName" >把学生名给父级</button>
</template>
...
methods: {
    sendStudentName() {
        // 触发父级Student组件实例身上的student事件
        this.$emit('student', this.name)
    }
}

三、全局事件总线(所有组件可以直接绑定某事件的一种方法, 不局限于衔接的父子级之间)

1.添加vm作为全局事件总线:

new Vue({
  render: h => h(App),
  beforeCreate() {  // 注意添加时刻
    Vue.prototype.$bus = this  // 在Vue原型上添加vm作为全局事件总线 目的:借助使用vm实例上的事件方法$on、$emit、$off等
  }
}).$mount('#app')

2.事件绑定:

  // 事件回调函数
methods: {
  deleteTodo(id) {
    this.todos = this.todos.filter(todo => todo.id !== id)
  }
},
mounted() {  // 注意绑定时刻
  this.$bus.$on('deleteTodo', this.deleteTodo)  // 在全局事件总线上将“deleteTodo”事件绑定在此组件上(意义就在于可以在任意组件“mounted()”上绑定该事件)
}

3.事件触发:

<template>
    <button class="btn btn-danger" @click="handleDelete(todo.id)">删除</button>
</template>

<script>
    export default {
      name: 'MyItem',
      methods: {
        handleCheck(id) {
          this.checkTodo(id)
        },
        handleDelete(id) {
          if(confirm('确定删除吗?')) {
            this.$bus.$emit('deleteTodo', id)  // 触发全局事件总线上的绑定事件
          }
        }
      }
</script>

四、脚手架搭建流程

下载与安装:

1.配置npm淘宝镜像下载CLI包:“npm config set registry
https://registry.npm.taobao.org”
2.使用@vue/cli包安装CLI:使用“npm install -g @vue/cli”全局安装

创建项目脚手架:

1.目标目录下:使用“vue create xxx(文件名)”➡创建项目脚手架
2.项目文件下:使用“npm run serve”➡开启当前目录npm服务器,启动项目

脚手架结构