首页 > vue如何使用组件?

vue如何使用组件?

我的目录结构如下:

 -components
     test.vue
 -dist
     app.js
 -src
     app.js
     app.vue
     vue.js
 -index.html
 -gulpfile.js
 -package.json

代码如下:

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>cityList</title>
</head>
<body>
    <div>111</div>
    <script type="text/javascript" src="dist/app.js"></script>
</body>
</html>

app.js

var Vue = require('vue'); 
new Vue(require('./app.vue'));

app.vue

<template>
<div id="box">
    <input type="text">
</div>
</template>

<script>
module.exports = {
    components : {
        'test' : require('../components/test.vue')
    }
}
</script>

test.vue

<style>
    body{
        background-color: #ccc;
    }
</style>
<template>
    <inputbox>123</inputbox>
    <p>test.vue已经加载</p>
</template>
<script>

module.exports = {
    events: {
        test: function (data) {
            console.log('run it.');
        }
    }
} 

</script>

gulpfile.js


var gulp = require('gulp')
var webpack = require('gulp-webpack')
var named = require('vinyl-named')


var appList = ['app','./test','../index']


gulp.task('default', ['bundle'], function() {
  console.log('done')
})

gulp.task('bundle', function() {
  return gulp.src(mapFiles(appList, 'js'))
    .pipe(named())
    .pipe(webpack(getConfig()))
    .pipe(gulp.dest('dist/'))
})

gulp.task('watch', function() {
  return gulp.src(mapFiles(appList, 'js'))
    .pipe(named())
    .pipe(webpack(getConfig({watch: true})))
    .pipe(gulp.dest('dist/'))
})


/**
 * @private
 */
function getConfig(opt) {
  var config = {
    module: {
      loaders: [
        { test: /\.vue$/, loader: 'vue'}
      ]
    },
    devtool: 'source-map'
  }
  if (!opt) {
    return config
  }
  for (var i in opt) {
    config[i] = opt[i]
  }
  return config
}

/**
 * @private
 */
function mapFiles(list, extname) {
  return list.map(function (app) {return 'src/' + app + '.' + extname})
}

现在,我想在页面中显示test.vue和app.vue的内容。
但是,页面上只显示了background-color这一个样式,其他都没显示到,这是什么问题呢?


请参考 vue-hackernews 的组织方式 : https://github.com/vuejs/vue-hackernews


更新:
完整可运行的代码放在了 https://github.com/yangjunjun/vue-pack-demo (使用 webpack 来构建)


你要明白 Vue 中组件的用法(请参考:http://cn.vuejs.org/guide/components.html)

index.html 修改为如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>cityList</title>
</head>
<body>
    <div>111</div>
    <app></app>
    <script type="text/javascript" src="dist/app.js"></script>
</body>
</html>

app.js 修改为如下:

var Vue = require('vue'); 
var App = require('./app.vue'); // 返回的是一个组件,必须注册才能使用
new Vue({
  el:'body',
  components:{
    app: App
  }
});
【热门文章】
【热门文章】