2017年9月30日 星期六

[Vue] Components - single file

  Vue.js    Components     Single file


Introduction


We will create reusable component with single file.


Related articles

2.  [Vue] Single file



Environment


vue-cli 2.8.2


Implement


We will use webpack-simple project template for example.
Use the following command to create one.

$ vue init webpack-simple {myapp}





Single file

App.vue

<template>
    <table class="table">
        <tbody>
            <tr>
                <th>Title</th>
                <th>Year</th>
                <th>Composer</th>
            </tr>
            <tr v-for="opera in operas">
                <td>{{ opera.Title }}</td>
                <td>{{ opera.Year }}</td>
                <td>{{ opera.Composer }}</td>
            </tr>
        </tbody>
    </table>
</template>
<script>
    module.exports = {
        props: ['operas'],
        data: function () {
            return {
            }
        }
    }
</script>
<style>
    th {
        color: red
    }
</style>




main.js

import Vue from 'vue'
import App from './App.vue'

var app = new Vue({
    el: '#app',
    components: { App },
    data: {
        operas: [],
    },
    methods: {
        getOperas: function () {
            return axios.get('http://localhost:36321/api/RestApi/Get');
        }
    },
    mounted: function () {
        var vm = this;

        vm.getOperas().then(response => {
            vm.operas = response.data;
            console.log(vm.operas);
        });
    }
})


Notice that we have to import the single file, App.vue and declare it in components.


HTML

<div id="app">
      <app :operas="operas"></app>
</div>




Result:







Reference





沒有留言:

張貼留言