Vue props 自定义属性

Vue About 1,932 words

自定义属性

组件中预定义一些字段,在其他组件引用时传入对应的值,起到复用的作用。

注意

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "init"

props中的属性建议是只读的。虽然可以修改,但控制台会出现警告。

建议如果需要修改,可再赋值给data中的变量。

简单定义 props

以数组方式定义一个自定义的变量init用于外部传入。

MyComponent

<template>
  <div>
    <p>
      my component
      count: {{ count }}
      init: {{ init }}
    </p>

    <button @click="add">Add</button>
  </div>
</template>

<script>
export default {
  name: "MyComponent",
  props: ["init"],
  data() {
    return {
      count: this.init
    }
  },
  methods: {
    add() {
      this.count++;
    }
  }
}
</script>

引用 MyComponent 的组件

使用:initv-bind:init简写为:init)表示传入的是JS代码,所以传入的是Number类型。

如果单纯传入字符串也可以是<MyComponent init="字符串"></MyComponent>

如果是:init方式传入字符串是<MyComponent :init="'字符串'"></MyComponent>(加入''单引号)。

<template>
  <div>
    <MyComponent :init="5"></MyComponent>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
}
</script>

更多属性定义 props

props: ["init"]数组方式定义传入的属性,不能设置更多属性的选项,比如类型、默认值、是否必须等。

可使用props: {}对象方式。

type:类型,约定传入的值必须是符合设定的类型。

default:默认值,当外部组件不传值的时候将使用默认值。

required:是否必须,但设置为true则必须传入值(default选项失效)。

备注:如果只想限定类型,也可以简写为属性: 类型,比如:msg: String

<template>
  <div>
    <p>
      my component
      count: {{ count }}
      init: {{ init }}
    </p>

    <button @click="add">Add</button>
  </div>
</template>

<script>
export default {
  name: "MyComponent",
  props: {
    init: {
      type: Number,
      default: 0,
      required: true
    },
    msg: String
  },
  data() {
    return {
      count: this.init
    }
  },
  methods: {
    add() {
      this.count++;
    }
  }
}
</script>
Views: 983 · Posted: 2022-12-24

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh