在 Vue 中使用 v-bind
在 Vue 中, v-bind
允许您将 HTML 属性绑定到 JavaScript 表达式。这种单向数据绑定有两个广泛的用例:
- 绑定到内置属性,例如
href
或者class
- 将 props 传递给子组件
绑定到内置属性
您可以使用 v-bind
将内置的 HTML 属性绑定到 JavaScript 表达式。
例如,您可以创建一个链接 href
绑定到 data
方法。 当 link
字段发生变化的时候,同时 href
属性也会跟着改变。
const app = new Vue({
data: () => ({ link: 'http://google.com' }),
// Initially, the link will go to Google...
template: `
<a v-bind:href="link">My Link</a>
`
});
// Now, the link will go to Twitter.
app.$data.link = 'http://twitter.com';
您可以将此语法用于一些很酷的用例,包括 动态内联 style
属性 。
const app = new Vue({
data: () => ({ color: 'blue' }),
// Initially, will show "blue text" in blue font.
template: `
<div v-bind:style="{ color }">{{color}} text</div>
`
});
// Now, it will show "green text" in green font.
app.$data.color = 'green';
道具
你也可以使用 v-bind
将 道具传递给子组件 。
// `props` is an array of prop names this component accepts. If you
// don't explicitly list a prop in `props`, you won't be able to use
// it in your template.
Vue.component('hello', {
props: ['name'],
template: '<h1>Hello, {{name}}</h1>'
});
// The app tracks `name` as internal state, and there's an input to
// modify `name` using `v-model`. Then, `v-bind:name` passes `name` as
// a prop to the `hello` component.
const app = new Vue({
data: () => ({ name: 'World' }),
template: `
<div>
<div>
<input v-model="name"></input>
</div>
<hello v-bind:name="name"></hello>
</div>
`
});
速记
这 v-bind
部分 v-bind:prop
是可选的。 你也可以使用 :prop
。
大多数大型 Vue 代码库使用 :prop
并避免打字 v-bind
。
const app = new Vue({
data: () => ({ link: 'http://google.com' }),
// `:href` is the same ad `v-bind:href`, just more concise.
template: `
<a :href="link">My Link</a>
`
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论