在 Vue 中使用 v-bind

发布于 2022-08-17 12:39:05 字数 2756 浏览 125 评论 0

在 Vue 中, v-bind 允许您将 HTML 属性绑定到 JavaScript 表达式。这种单向数据绑定有两个广泛的用例:

绑定到内置属性

您可以使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

文章
评论
28 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文