Vue.js

Q&A

属性绑定为什么用 v-bind 替代 Mustache

注:这里用 [[ ]] 代替 Mustache 的胡须符号,避免被 Jekyll 解析掉。

Q:

在 0.12 版本的时候,可以这样绑定属性与数据:

<item page=[[ displayPage ]]></item>

后来改成了这样:

<item v-bind:page="displayPage"></item>

现在造成有两种绑定数据的方法,一种是属性,用 v-bind ,一种是文本,用 [[ ]],而原来只要一种 [[ ]] 就够了。

这样增加复杂度的改动有什么原因呢?

A:

<img src = [[ img_url ]]> 

这种浏览器会发送一个错误的 GET 请求,用 v-bind,

<img :src = "img_url"> 

就不会。

html 都是给浏览器引擎解析的 <img src=[[ img_url ]]> ,在 vue 处理 img_url 之前,浏览器会得到一个错误的 src 值,即[[ img_url ]],所以会立即发送一个 get 请求,而 :src 或者 v-bind:src 浏览器根本不认识,一个没有 srcimg ,浏览器是不会发出请求的。

所以 2.0 是统一了接口,去除了不能通用的 [[ ]]

(via V2EX.com)1

组件的 Watch 选项里可以使用 this 吗?

Q:

watch: {
  'params.page': 'update' // TODO: Cannot use `this.update` here, why?
},
methods: {
  update: function(){
    store.fetchItemsByPage(this.params.page, function(items){
      this.items = items;
    }.bind(this));
  }
}

以上代码,如果把 'params.page': 'update' 换成 'params.page': this.update 将不会工作。

A:

The reason has nothing to do with Vue specifically.

watch: {
  'params.page': this.update
}

In the above code, this.update will be evaluated when the module file is loaded, which is long before the component is actually created from these options.

At this point, this is not the component instance (because this component instance does not exist yet), it’s rather pointing to the module scope, which is undefined.

Q:

if this.update in watch: { } object doesn’t work, then how could this.update in methods: { } object work?

like below:

methods: {
  funcName: function(){
    this.update(); // This will work
  }
}

A:

Well in this case, ít is within a function. So it will only be evaluated when that funcion is called - which happens after the component instance exists.

(via forum.vuejs.org)2

How to style components from outside

A:

It depends a bit on how the component in question is set up.

  1. Override in the parent. Generally, you can always override the coomponent’s stles in the parent - if the component uses .classA to add a certain style, add class="wrapperClass" to the component in the parent, and in the styling, use .wrapperClass.ClassA to override the CSS.

    But if the component used <style scoped>, you will have a hard time with that due to collisions in specificity.

  2. Pass classes as props. Some components offer the ability to pass classes as props, which are then applied to the components template instead of/additionally to the component’s default ones - but the CSS for those classes still has to be added in the parent (or a global stylesheet).

    This of course means that the component’s author has to offer such a mechanism, you can’t really add it yourself.

(via forum-archive.vuejs.org)3