关于vue.js:Vue三大核心概念之一属性

1.自定义属性props:即组件中申明的属性,子类承受父类的值
2.原声属性attrs:没有申明的属性,默认主动挂在到组件根元素上,设置inheritAttrs为false可能敞开主动挂载
3.非凡属性class,style挂载到组件根元素上,反对字符串,对象,数组等多种语法.

定义属性的两种形式
1.props: [‘title’, ‘likes’, ‘isPublished’, ‘commentIds’, ‘author’] 无奈对属性值进行校验
2.能够对属性值进行校验

props: {
    // 根底的类型查看 (`null` 和 `undefined` 会通过任何类型验证)
    propA: Number,
    // 多个可能的类型
    propB: [String, Number],
    // 必填的字符串
    propC: {
      type: String,
      required: true
    },
    // 带有默认值的数字
    propD: {
      type: Number,
      default: 100
    },
    // 带有默认值的对象
    propE: {
      type: Object,
      // 对象或数组默认值必须从一个工厂函数获取
      default: function () {
        return { message: 'hello' }
      }
    },
    // 自定义验证函数
    propF: {
      validator: function (value) {
        // 这个值必须匹配下列字符串中的一个
        return ['success', 'warning', 'danger'].indexOf(value) !== -1
      }
    }
  }

案例:

子组件

<template>
  <div>
     name:{{name}}
     <br/>
     type:{{type}}
     <br/>
     list:{{list}}
     <br/>
     isView:{{isView}}
     <br/>
     <button @click="handClick">change</button>
  </div>
</template>

<script>
export default {
    //子组件的名称
    name:"Props",
    props:{
        name:String,
        type:{
            validator:function(val){
                return ["入门","小站","Rumenz"].includes(val)
            }
        },
        list:{
            type:Array,
            default:()=>[]
        },
        isView:{
            type:Boolean,
            default:false
        },
        onChange:{
            type:Function,
            default:()=>{}
        }
    },
    methods:{
        handClick(){
            this.onChange(this.type==="入门"?"one":"tow")
        }
    }

}
</script>

<style>

</style>

父组件利用子组件

<template>
<div id="app">
   {{msg}}
   <!--属性绑定格局 :[自组件的属性]:[父组件的属性]-->
   <Props 
   :name="name"
   :type="type"
   :list="list"
   :isView="view"
   :onChange="onChange"
   />
  
</div>
</template>

<script>
//导入子组件
import Props from './components/Props'

export default {
  name: 'App',
  data() {
        return {
            msg: "hello 入门小站",
            name:"name",
            type:"入门",
            list:['入门','小站'],
            view:true
        }
    },
    methods: {
      onChange(val){
        this.name=val;
      }
    },
  components: {
    Props //必须申明子组件
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

源码:https://github.com/mifunc/rum…

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理