vue100-props的required必填项

<template>
  <div class="hello">
    <h3>{{ init }}</h3>
    <button @click="changeName">+1</button>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  //props是自定义属性 为当前属性定义初始值
  //对象设置默认值
  props: {
    init: {
      default: 9,
      type:Number,
      required:true
    },
  },
  data() {
    return {
      count: 0,
    };
  },
  methods: {
    changeName() {
      //报错 this.props是只读的
      this.init++;
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
h3 {
  margin: 40px 0 0;
}
</style>

只校验有没有传这个属性

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue.js 中,可以使用 prop 校验来确保传入组件的数据满足一定的要求。你可以通过在子组件中定义 props,并且在父组件中传递值来实现这一点。 如果你想要校验子组件的必填,可以使用 `required` 校验器。下面是一个示例: 子组件: ```vue <template> <div> <!-- ... --> </div> </template> <script> export default { name: 'MyChildComponent', props: { name: { type: String, required: true // 必填 } // ... } } </script> ``` 父组件: ```vue <template> <div> <my-child-component :name="childName" /> </div> </template> <script> import MyChildComponent from './MyChildComponent.vue' export default { name: 'MyParentComponent', components: { MyChildComponent }, data() { return { childName: '' // 未填写 } } } </script> ``` 在这个示例中,子组件 `MyChildComponent` 中的 `name` prop 被标记为必填。在父组件 `MyParentComponent` 中,我们传递了一个空字符串作为 `childName` 的值,这将导致 Vue.js 抛出一个警告。 如果你想要在父组件中检查子组件是否填写了必填,可以使用 `$refs` 来获取子组件实例,并检查其 `name` prop 是否已填写。下面是一个示例: ```vue <template> <div> <my-child-component ref="child" :name="childName" /> <button @click="submit">提交</button> </div> </template> <script> import MyChildComponent from './MyChildComponent.vue' export default { name: 'MyParentComponent', components: { MyChildComponent }, data() { return { childName: '' // 未填写 } }, methods: { submit() { if (!this.$refs.child.name) { alert('请填写必填') return } // ... } } } </script> ``` 在这个示例中,我们在 `MyChildComponent` 上使用了 `ref` 属性来获取子组件实例,然后在 `submit` 方法中检查 `name` prop 是否已填写。如果未填写,则会显示一个提示消息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端大歌谣

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值