laravel 5 vue setup unclear

2019-08-02 07:06发布

问题:

I've tried about everything now but I can't get vue.js to work on Laravel, there doesn't seem to be anything concrete around that says put x in file y to get it working.

I've tried about everything with npm, composer but i can't even get a basic example to work. It's very unclear to me what I need and where it needs to go.

I am using blade to extend from an app.layout view but it's unclear wether i need to add code to assets/js/app.js or just use script src="" tags in my default app layout.

app.js

require('./bootstrap');

window.Vue = require('vue');

Vue.component('example', require('./components/Example.vue'));

const app = new Vue({
   el: '#app'
});

var app5 = new Vue({
  el: '#app-5',
   data: {
     message: 'Hello Vue.js!'
   }  ,
   methods: {
     reverseMessage: function () {
      this.message = this.message.split('').reverse().join('')
    }
   }
 })

app.layout.blade.php

<script src="{{asset('/js/app.js')}}"/></script>

..some more html

<body id="app">
   <div id="app-5">
   <p>@{{ message }}</p>
   <button v-on:click="reverseMessage">Reverse Message</button>
   </div>
   </body>

..more html

回答1:

why you define two Vue const?

this part of js code is no needed:

const app = new Vue({
   el: '#app'
});

remove that line and test it :

require('./bootstrap');

window.Vue = require('vue');

Vue.component('example', require('./components/Example.vue'));



var app5 = new Vue({
  el: '#app-5',
   data: {
     message: 'Hello Vue.js!'
   }  ,
   methods: {
     reverseMessage: function () {
      this.message = this.message.split('').reverse().join('')
    }
   }
 })

but remmember your vuejs work should be beetween:

<div id="app-5"> vuejs codes should be run here </div>

Don't forget running npm run watch or npm run dev to compile

if you have error and problem with this way you can skip to second way


Second Way:

create vue-script.js file in public/js/ directory

vue-script.js:

var app5 = new Vue({
  el: '#app',
   data: {
     message: 'Hello Vue.js!'
   }  ,
   methods: {
     reverseMessage: function () {
      this.message = this.message.split('').reverse().join('')
    }
   }
 })

create sample.blade.php file in resources/views/ directory

sample.blade.php:

<!DOCTYPE html>
<html>
<head>
<title>test page</title>
</head>

<body>
  <div id="app">
    @{{ message }}
    <button v-on:click="reverseMessage">Reverse Message</button>
  </div>
<script src="https://unpkg.com/vue"></script>
<script src="{{ asset('js/vue-script.js') }}"></script>

</body>
</html>

then in routes/web.php:

Route::get('testvue', function() {
    return view('sample');
});

and go to url : /testvue in your browser