使用VUE写一段时间项目的我的总结-组件篇

笔者yy:哭泣,为何不能够设置本身看,我只是作个笔记,好羞涩啊html

组件篇

组件建立

  1. var mycomponent=Vue.extend({template:'',methods:{}}) 这个是感受更酷的写法,用函数式
  2. var myconmponent={template:'',methods:{}} 这个是语法糖

组件引入方式(全家桶式的)

import 组件名 from 'url'
components:{组件名A:组件名B}vue

组件名A为父组件中要使用html名,组件B为import的组件名,当两个名字同样时,能够用es6的语法糖,直接写为 {components:{组件名}es6

  • 根据规范,子组件的标签最好为hs-name-来分开,防止为了和之后的HTML标签冲突
  1. 局部引入
    在每一个vue文件或者vue示例中引入,由于这个式局部引入,能够同时引入多个,因此component为复数,components
import Mybutton from 'url1'
import Myselect from 'url2'
 {components:{'my-button':Mybutton,'my-select':Myselect}}
复制代码
  1. 全局引入(在main.js/app.js文件)
import Mybutton from 'url'
Vue.component('my-button',Mybutton)
复制代码

组件传值(重点)

父向子传值

  • 第一种prop
  1. 父组件
<son :title="父传子"></son>
复制代码
  1. 子组件
<template>{{title}}</template>
1. props:['title','id','name']//直接写
2. props:{title:String} // 基础类型检测, null意味着任何类型都行
3. props:{title: [String, Number]}// 多种类型
4. props:{title:{type: String,required: true}}  // 必传且是String
5.props:{title:{type: Number,default: 101}}, //数字有默认值
6. props:{title:{type: Object, default: function() {
    console.log("propE default invoked.");
    return { message: "I am from propE." };
   }} // 数组、默认值是一个工厂函数返回对象
7. props:{title:{isValid: function(value) {return value > 100;}}}// 自定义验证函数,若是传入的值没有大于100则会警告
复制代码

子组件理论上是不能修改处理父组件传过来的值的,只能最多把值进行赋值给别的变量再进行处理数组