当前位置: 移动技术网 > IT编程>脚本编程>vue.js > 详解vue中组件参数

详解vue中组件参数

2018年08月08日  | 移动技术网IT编程  | 我要评论

寻花问柳平天下txt,格里芬扣篮视频,dsa

我们来聊一下vue中的组件参数.

1.vue中组件参数

我们可以为组件的 prop 指定验证要求,例如你知道的这些类型。如果有一个需求没有被满足,则 vue 会在浏览器控制台中警告你。这在开发一个会被别人用到的组件时尤其有帮助。

我们来看下最为简单和常见的vue代码

<div id="root">
      <item content="hello"></item>
    </div>
    <script>
      vue.component("item",{
        props:["content"],
        template:"<div>{{content}}</div>"
      })
      new vue({
        el:"#root"
      })
    </script>

这是一个最简单的创建组件和父组件向子组件的例子,但是我们在是否可以考虑一下,如果我希望父组件向子组件传递参数的时候是个数字类型呢?又或者是布尔类型呢?所以我们在这里就必须要对父组件传递过来的参数做一个校验。

<div id="root">
      <item content="hello"></item>
    </div>
    <script>
      vue.component("item",{
        props:{
          content:string
        },
        template:"<div>{{content}}</div>"
      })
      new vue({
        el:"#root"
      })
    </script>

我们对第一个例子的代码进行了修改,我们把子组件中的props属性,改为一种对象的形式,而且我们也约束了父组件传递过来的content为string类型,但是还会有这样的一种情况出现,请看下面的代码:

<div id="root">
      <item content="1"></item>
    </div>
    <script>
      vue.component("item",{
        props:{
          content:string
        },
        template:"<div>{{content}}</div>"
      })
      new vue({
        el:"#root"
      })
    </script>

我们改变了父组件中content的值等于1,那么我们就很自然的把content理解为数字类型,那么页面就会出现报错的提示.但是我们打开页面后,并没有浏览器报错。这又是为什么呢?

在vue中,默认传递的值都是字符串,如果你想要传递一个数字,那么必须在content前面添加一个:

我们希望它出现报错,那么我们就应该这么修改以上的代码。

<div id="root">
      <item :content="1"></item>
    </div>
    <script>
      vue.component("item",{
        props:{
          content:string
        },
        template:"<div>{{content}}</div>"
      })
      new vue({
        el:"#root"
      })
    </script>

那么这个时候,vue就会给我们一个代码错误提示。如果我们希望它不报错,那么我们修改一下content里面的类型

<div id="root">
      <item :content="1"></item>
    </div>
    <script>
      vue.component("item",{
        props:{
          content:number
        },
        template:"<div>{{content}}</div>"
      })
      new vue({
        el:"#root"
      })
    </script>

当然了,content也是可以接受一个数组的,用来判断它父组件为子组件传递的多个参数。

<div id="root">
      <item :content="1"></item>
    </div>
    <script>
      vue.component("item",{
        props:{
          content:[string,number]
        },
        template:"<div>{{content}}</div>"
      })
      new vue({
        el:"#root"
      })
    </script>

除了数组形式,我们也可以写成对象的形式。那么对象的形式,vue为我们提供了各种可选的参数。

<div id="root">
      <item content="hello world"></item>
    </div>
    <script>
      vue.component("item",{
        props:{
          content:{
            type:string,
            required:true,
            default:"asd",
            validator:function(value){
              return (value.length>5)
            }
          }
        },
        template:"<div>{{content}}</div>"
      })
      new vue({
        el:"#root"
      })
    </script>

总结

以上所述是小编给大家介绍的vue中组件参数,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网