仅将视图组件安装在单个Rails视图上

时间:2019-03-16 18:01:51

标签: ruby-on-rails vue.js

我创建了一个视图组件来处理一些选择... 我需要将此组件加载到单个Rails视图中。

我用以下方法初始化组件:

import Vue from 'vue'
import Product from '../components/product.vue'
import axios from 'axios';

Vue.prototype.$http = axios

document.addEventListener('DOMContentLoaded', () => {
  document.body.appendChild(document.createElement('app'))
  console.log('caricato Vue');
  const app = new Vue({
    render: h => h(Product)
  }).$mount('#product_search')
})

在Rails页面中,我有一个#product_search div

Rails尝试在每个页面上加载组件并给我错误:

vue.runtime.esm.js:619 [Vue warn]: Cannot find element: #product_search

为什么?

1 个答案:

答案 0 :(得分:0)

因为Vue会在#product_search准备就绪时(即在应用程序的每一页上)尝试渲染组件(在document上)。

您可以添加一个条件来防止空错误:

document.addEventListener('DOMContentLoaded', () => {
  let element = document.querySelector('#product_search')
  if (element) {
    document.body.appendChild(document.createElement('app'))
    console.log('caricato Vue');
    const app = new Vue({
      render: h => h(Product)
    }).$mount('#product_search')
  }
})
相关问题