Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[vue]vue学习and云采超市app实践(三、vue组件) #11

Open
songhlc opened this issue Jul 9, 2016 · 0 comments
Open

[vue]vue学习and云采超市app实践(三、vue组件) #11

songhlc opened this issue Jul 9, 2016 · 0 comments
Labels

Comments

@songhlc
Copy link
Owner

songhlc commented Jul 9, 2016

什么是组件

vue组件在这里是可扩展的html自定义元素,封装可复用的代码。比如

<div id="example">
  <my-component></my-component>
</div>

使用组件

  • 组件注册
var MyComponent = Vue.extend({
  // 选项...
})
// 全局注册组件,tag 为 my-component
Vue.component('my-component', MyComponent)
  • 局部注册
var Child = Vue.extend({ /* ... */ })

var Parent = Vue.extend({
  template: '...',
  components: {
    // <my-component> 只能用在父组件模板内
    'my-component': Child
  }
})

Props

组件实例的作用域是孤立的。这意味着不能并且不应该在子组件的模板内直接引用父组件的数据。可以使用 props 把数据传给子组件。

  • 声明props
Vue.component('child', {
  // 声明 props
  props: ['msg'],
  // prop 可以用在模板内
  // 可以用 `this.msg` 设置
  template: '<span>{{ msg }}</span>'
})
  • 传入参数
<child msg="hello!"></child>
  • 动态props
<child v-bind:my-message="parentMsg"></child>
  • props绑定类型
    props默认是单向绑定,当父组件的属性变化时,将传导给子组件,但是反过来不会,防止子组件改变父组件属性。不过也支持通过.sync 或 .once 绑定修饰符显式地强制双向或单次绑定。

关于父子组件的通信

  • 父子组件通信
    • 1.父链:通过this.$parent访问父组件;
    • 2.自定义事件
    • 3.v-on 绑定自定义事件
      不详细描述了 看官方文档里组件页的详细介绍吧

通过slot对组件进行组合

例子:

<app>
  <app-header></app-header>
  <app-footer></app-footer>
</app>

疑问:如果app下也有自己的模板,怎么处理。

父组件模板

<my-component>
  <p>This is some original content</p>
  <p>This is some more original content</p>
</my-component>

子组件(my-component)模板

<div>
  <h1>This is my component!</h1>
  <slot>
    如果没有分发内容则显示我。
  </slot>
</div>

渲染结果

<div>
  <h1>This is my component!</h1>
  <p>This is some original content</p>
  <p>This is some more original content</p>
</div>

如果没有slot,渲染结果

<div>
  <h1>This is my component!</h1>
</div>

====
以上就是个人觉得初识vue需要了解到的vue 组件相关的一些细节,其实还有很多详细的内容,都欢迎到官网进行查看吧。

下一篇计划是介绍一下vue-router并结合vue-router来做一个spa webapp,敬请期待咯

@songhlc songhlc added the VUE label Jul 21, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant