为什么我的Vue.component没有在HTML页面上呈现?

时间:2019-03-20 16:30:38

标签: javascript vue.js axios

我正在尝试创建Vue.component,但是HTML页面无法呈现他(chrome不会给出错误)。请告诉我我哪里做错了,我做错了什么?

main.js:

Vue.component('product-type-component', {
data() {
    return {listProductType: []}
},
beforeMount(){
    axios.get('http://localhost/admin/getListProductType')
    .then(response => {
        this.listProductType = response.data
    })
},
template:'<option v-for="index in listProductType" v-bind:value="index.id +  "/" +  index.name">{{index.name}}</option>'
});

var vm = new Vue({
    el: "#mainForm",
    data:{...},
beforeMount(){...},
methods:{...}
});

index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="style/style.css">
  <title></title>
</head>
<body>
  <div id="mainForm">
    <select v-model="selectItem">
        <product-type-component></product-type-component>
    </select>
  </div>
<script type="text/javascript" src="script\vue\vue.js"></script>
<script src="script\axios\axios.min.js"></script>
<script type="text/javascript" src="script\main.js"></script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

嗯,我想您没有意识到您将Vue作为node添加到div#mainForm

作为同级,选择节点不在SPA的范围内。而且,我不确定-但是我认为在安装过程中,所有其他节点都从div#mainForm

中删除了

您更想要这样:

import Vue from "vue";

Vue.config.productionTip = false;
Vue.component("product-type-component", {
  data() {
    return { listProductType: [] };
  },
  beforeMount() {
    // axios.get('http://localhost/admin/getListProductType')
    // .then(response => {
    //     this.listProductType = response.data
    // })
  },

  template: "<option " + /* v-for... */ ">some option</option>"
});

new Vue({
  el: "#app",
  template: `<select><product-type-component></product-type-component></select>`
});

工作示例:sandbox

import Vue from "vue";
import { METHODS } from "http";
import * as axios from "axios";
Vue.config.productionTip = false;
var productTypeComponent = Vue.component("product-type-component", {
  data() {
    return { listProductType: [] };
  },
  beforeMount() {
    axios.get("https://dog.ceo/api/breeds/list/all").then(response => {
      console.log(response);
      this.listProductType = Object.keys(response.data.message);
    });
    console.log("///" + this.listProductType);
  },
  template:
    '<select><option v-for="(item, index) in listProductType" v-bind:value="item">{{item}}</option></select>'
});
var vm = new Vue({
  el: "#app",
  data: {},
  methods: {},
  template: `<div><product-type-component /></div>`
});