2017-03-13 249 views
6

考虑到有单一文件组件(如shown in the guide),的Vue 2组件样式没有Vue公司装载机

<style> 
.example { 
    color: red; 
} 
</style> 

<template> 
    <div class="example">hi</div> 
</template> 

如何同样的事情可以不Vue公司装载机在非模块化ES5/ES6环境做了什么?

考虑到风格的作用域,

<style scoped> 
.example { 
    color: red; 
} 
</style> 

是否有实施范围的CSS在非模块化的环境中,太办法?如果没有,有没有办法在模块化环境(Webpack)中实现它,但没有Vue加载器和自定义的.vue格式?

回答

5

而是在Vue的零件以template实例,你可以利用一个“近到'编译器替代'与渲染函数而不需要Vue加载器或编译器。您可以使用功能中的第二个参数添加任何其他属性,这将为您在样式上提供很大的灵活性。

渲染功能指南中部分获取更多信息,并允许在数据OBJ所有的选项:

https://vuejs.org/v2/guide/render-function

https://vuejs.org/v2/guide/render-function#The-Data-Object-In-Depth

注:在这里需要注意的是,该样式将仅适用于它声明的组件,所以它可能无法像CSS那样在同一个类的多个组件中使用。不知道这是否也是你想实现的。

一个例子,从迎合了这个用例文档:

Vue.component('example', { 
 
    // render function as alternative to 'template' 
 
    render: function (createElement) { 
 
     return createElement(
 
      // {String | Object | Function} 
 
      // An HTML tag name, component options, or function 
 
      // returning one of these. Required. 
 
      'h2', 
 
      // {Object} 
 
      // A data object corresponding to the attributes 
 
      // you would use in a template. Optional. 
 
      { 
 
       style: { 
 
        color: 'red', 
 
        fontSize: '28px', 
 
       }, 
 
       domProps: { 
 
        innerHTML: 'My Example Header' 
 
       } 
 
      }, 
 
      // {String | Array} 
 
      // Children VNodes. Optional. 
 
      [] 
 
    )} 
 
}); 
 

 
var example = new Vue({ 
 
    el: '#yourExampleId' 
 
});

+0

是的,谢谢,在我看来,render函数是现在唯一可行的方法。 – estus

0

它可以实现手动把范围,因为vue-loader自动执行。

这是文档的例子。在这种情况下添加某种类型的ID“_v-f3f3eg9”,以便仅为该元素的类范围。

<style> 
.example[_v-f3f3eg9] { 
    color: red; 
} 
</style> 

Vue.component('my-component', { 
    template: '<div class="example" _v-f3f3eg9>hi</div>' 
}); 
+0

但.vue文件,需要Vue公司装载机。如果没有Vue加载器,这怎么能实现呢? – estus

0

我用Rollup(+ Bublé)+ Vue.js所有的时间。这非常简单快捷。

汇总的配置是这样的:

import vue from 'rollup-plugin-vue'; 
import resolve from 'rollup-plugin-node-resolve'; 
import buble from 'rollup-plugin-buble'; 

const pkg = require('./package.json'); 
const external = Object.keys(pkg.dependencies); 

export default { 
    external, 
    globals: { vue: 'Vue' }, 
    entry: 'src/entry.js', 
    plugins: [ 
    resolve(), 
    vue({ compileTemplate: true, css: true }), 
    buble({ target: { ie: 9 }}) 
    ], 
    targets: [ 
    { dest: 'dist/vue-rollup-example.cjs.js', format: 'cjs' }, 
    { dest: 'dist/vue-rollup-example.umd.js', format: 'umd' } 
    ] 
}; 

我做了一个boilerplate repo

git clone https://github.com/jonataswalker/vue-rollup-example.git 
cd vue-rollup-example 
npm install 
npm run build 
+0

感谢这个例子,它是说明性的。不知道布布。然而,我感兴趣的是如何在纯JS中使用Vue,而不需要编译和构建。组件样式特别。 – estus

+0

哦,不,浏览器永远不会理解组件样式。必要的你需要一个构建步骤。 –

+0

我很确定它在Vue中可行,但不知道如何。只是因为Vue加载器应该编译.vue到* something *。正因为竞争对手的框架完全支持vanilla ES5,而不支持它,这对Vue来说是无稽之谈。 – estus