Software
laramix with vue-masonry package error
I'm wroking on laravel 5.4 project.
The question is vue-masonry(https://github.com/shershen08/vue-masonry) package doesn't work with the following error
Please help me to check my setting that are the wrong part.
Here is my app.js :
require('./bootstrap'); require('masonry-layout'); require('imagesloaded'); require('fancybox'); var vueMasonry = require('vue-masonry'); Vue.use(vueMasonry);the bootstrap.js still original without modify a word, and package.json is here:
{ "private": true, "scripts": { "dev": "npm run development", "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js", "watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js", "watch-poll": "npm run watch -- --watch-poll", "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js", "prod": "npm run production", "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js" }, "devDependencies": { "bootstrap-sass": "^3.3.7", "cross-env": "^3.2.3", "laravel-mix": "0.*", "lodash": "^4.17.4", "minifier": "^0.8.1", "stylus": "^0.54.5", "stylus-loader": "^3.0.1" }, "dependencies": { "axios": "^0.15.3", "fancybox": "^3.0.0", "imagesloaded": "^4.1.3", "jquery": "^3.1.1", "masonry-layout": "^4.2.0", "swiper": "^3.4.2", "vue": "^2.1.10", "vue-masonry": "^0.10.7" } }And the final Html is something like:
<div class="grid-wrap" v-masonry fit-width="true" transition-duration="0.3s" item-selector=".grid-item" fit-width="true" > <div v-masonry-tile class="grid-item" v-for="wall in walls"> <div class="grid-date"> @{{ wall.created_at }} </div> </div> </div>Make Vue elements draggable with jQuery UI
In my app, I make 2 ajax calls to pull in new data every 10 seconds. This data will often change. I want to make the Dom elements I create draggable.
- What is the best way to structure this within my apps?
- Is there a way to achieve this without calling $(elements).draggable() every time? There will be 1000+ DOM elements created in one of my apps.
var height = $(document).height(); var width = $(document).width(); $(function() { var app = new Vue({ el: '#main', data: { tables: [] }, methods: { loadTables() { $.ajax({ method: 'POST', dataType: 'json', url: base_url + 'tables/getTables/' + event_id }).done(data => { this.tables = data; }); }, computeOffsets(table) { return { top: (table.position_x * width) + 'px', left: (table.position_y * height) + 'px' } } }, mounted() { this.loadTables(); setInterval(() => { console.log("Getting Tables"); this.loadTables(); }, 10000); } }); var sidebar = new Vue({ el: '#sidebar', data: { people: [] }, methods: { isCheckedIn(person) { return person.reg_scan == null ? true : false; }, loadPeople() { $.ajax({ method: 'POST', dataType: 'json', url: base_url + 'users/getParticipants/' + event_id }).done(data => { this.people = data; }); } }, mounted() { this.loadPeople(); setInterval(() => { console.log("Getting People"); this.loadPeople(); }, 10000); } }); }); .table { position: absolute; } #sidebar { width: 10%; float: left; height: 500px; overflow-y: scroll; } .checked-in { background-color: lightgreen; } <link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script> <div id="sidebar"> <div v-for="person in people" :class="{'checked-in': isCheckedIn(person), 'person' : true}" :id="person.id"> {{person.first_name + ' ' + person.last_name}} </div> </div> <div id="main"> <div class='table' v-for="table in tables" :style="computeOffsets(table)"> {{table.name}} </div> </div>
Dna the Code of Life
vuejs start a timer for every record
I have this component rendered, I need to tell the users how much time remaining for each record displayed
I couldn't get anything worked out, I don't know any legible ways to work it out, so just trying calling out methods. I tried child components too but no avail.
<template> <div> <ul v-for="question in questions"> {{init_timer(secs)}} {{start_timer()}} <li> <a href="#" id="user-profile-text-link">{{question.name}}</a> <span class="question_clock">Validity : -- counter : {{time_remaining}} </span> </small> </li> </ul> </div> </template> <script> export default { data: function(){ return { questions: [], time_remaining : 1 }; }, methods: { init_timer: function(secs) { this.time_remaining = secs }, start_timer: function() { console.log('startiem') setTimeout(function () { this.time_remaining -= 1 }.bind(this), 1000) }, } , created: function(){ $.getJSON('/questions/json', function(response){ this.questions = response }.bind(this )); }, } </script>any help is much appreciated
Testing VueJS method inside of a promise witch is returned from a vuex action
I have a Vue component, witch is using a mapped action from a vuex store, which returns a promise. When the component calls the mapped action, and the mapped action is resolved, I am calling another vue method vm.$router.push(). I want to assert that the push method gets called. Here is my component, test, and some helper methods I created to sub out the component with vuex and vue-router.
Here is my .vue component with some console.logs to track what's going on.
<template> <div> <button @click="promise" class="click-promise">Promise</button> </div> </template> <script> import { mapActions } from 'vuex' export default { methods: { ...mapActions(['promiseAction']), promise(){ const vm = this vm.$router.push('/some/route') console.log('before promiseAction') console.log(vm.promiseAction()) return vm.promiseAction().then(function (response) { console.log('inside promiseAction') vm.$router.push('/some/other/route') }) } } } </script>Here is my test. I'm using Mocha, Karma, Chai, and jquery-chia
import Testing from '@/components/Testing' describe('Testing.vue', () => { const mount = componentHelper(Testing) it.only('assert something in a promise returned from an action', () => { const promise = new Promise(resolve => resolve('success')) const promiseAction = stubAction('promiseAction').returns(promise) const vm = mount() const routerPush = sinon.spy(vm.$router, 'push') $('.click-promise').click() expect(promiseAction).to.have.been.called expect(routerPush).to.have.been.calledWith('/some/route') //this passes return vm.$nextTick(() => { console.log('inside nextTick') expect(routerPush).to.have.been.calledWith('/some/other/routes') //this never happens }) }) })And here is my helpers file. I'm not sure if this is 100% neccisary, but I wanted to include everything in this post
import Vue from 'vue' import Vuex from 'vuex' import VueRouter from 'vue-router' Vue.use(Vuex) Vue.use(VueRouter) let div beforeEach(() => { // create a dom element for the component to mount to div = document.createElement('div') document.body.appendChild(div) }) afterEach(() => { // clean up the document nodes after each test Array.prototype.forEach.call(document.querySelectorAll('body *:not([type="text/javascript"])'), node => { node.parentNode.removeChild(node) }) }) // stub out a store config object const storeConfig = { actions: {} } /** * Set up a function that will attach the mock store to the component * and mount the component to the test div element * * Use like this: * const mount = componentHelper(YourComponent) * do some setup * call mount() to instantiate the mocked component * * @param component * @returns {function()} */ window.componentHelper = function (component) { const router = new VueRouter({}) return () => { // 1. attaches the stubbed store to the component component.store = new Vuex.Store(storeConfig) component.router = router // 2. mounts the component to the dom element // 3. returns the vue instance return new Vue(component).$mount(div) } } /** * Creates an action to be added to the fake store * returns a sinon stub which can be asserted against * @param actionName */ window.stubAction = (actionName) => { // 1. create a stub const stub = sinon.stub() // 2. create the action function that will be placed in the store and add it to the store storeConfig.actions[actionName] = function (context, ...args) { // 3. when this action is called it will call the stub // return the stub so you can assert against the stubbed return value // example: stubAction('fakeAction').returns('xyz') return stub(...args) } // 4. return the stub that was placed in the return of the action for assertions return stub }When I run this test this is what I get.
LOG LOG: 'before promiseAction' LOG LOG: Promise{_c: [], _a: undefined, _s: 1, _d: true, _v: 'success', _h: 0, _n: true} Testing.vue ✓ assert something in a promise returned from an action PhantomJS 2.1.1 (Linux 0.0.0): Executed 1 of 4 SUCCESS (0.045 secs / 0.018 secs) TOTAL: 1 SUCCESS =============================== Coverage summary =============================== Statements : 31.58% ( 6/19 ) Branches : 100% ( 0/0 ) Functions : 0% ( 0/2 ) Lines : 31.58% ( 6/19 ) ================================================================================ LOG LOG: 'inside nextTick' ERROR LOG: '[Vue warn]: Error in nextTick: "AssertionError: expected push to have been called with arguments /some/other/routes /some/route /some/other/routes " (found in <Root>)' ERROR LOG: AssertionError{message: 'expected push to have been called with arguments /some/other/routes /some/route /some/other/routes ', showDiff: false, actual: push, expected: undefined, stack: undefined, line: 210, sourceURL: 'http://localhost:9877/absolute/home/doug/Code/projects/vue-testing-sandbox/node_modules/chai/chai.js?ab7cf506d9d77c111c878b1e10b7f25348630760'} LOG LOG: 'inside promiseAction'As you can see the test passes, but the code inside of the promise does not run until after the test is done. I'm talking about this section
return vm.promiseAction().then(function (response) { console.log('inside promiseAction') vm.$router.push('/some/other/route') })I also logged out the promise function console.log(vm.promiseAction()) and you can see it is what you would expect.
How can I get the test to wait for the promise? I thought nextTick might be the answer, but it doesn't seem to be working.
Thanks for any help.
Is there a way to attach an event handler to a drawer opening and closing?
I'm working on a game for my son and I would like the game to pause automatically when the drawer is opened. In order to accomplish that, I want to associate a dispatch() call to the drawer opening event.
Populating table with object containing an array in vuejs?
I am trying to populate table with an object which contains an array.I am able to successfully do that but i want each task name to have its own row right now they are coming in a single row.
{level_image :"image"level_name:"1"task_name: ["game","taskgame","jenga"]}
<tr v-for="tel in result" :key="tel.level_image" :pey="tel.level_name"> <td>{{tel.level_image}}</td> <td>{{tel.level_name}}</td> <td v-for="task in tel.task_name">{{task}}</td> </tr>Download fileResult docx on client side
I am working on a client-server application, and at the moment i am returning a file result in my web api controller, like this:
FileContentResult result = new FileContentResult(System.IO.File.ReadAllBytes(docDestination), "application/msword") { FileDownloadName = "myFile.docx" }; return result;on my client side i receive the response like this:
i thaught at begin that the browser detects the file automaticly and fires the download dialog, but no, so i tried to treat the result as a blob like this:
.then(response => { console.log("here lives the response:", response); var headers = response.headers; var blob = new Blob([response.bodyText], { type: headers['application/msword'] }); var link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = "Filename"; link.click();the download fires, but the content is not identified as docx file, and his content is broken.
Any tip on how to do it?
Thanks
How to filter YouTube URL when entered in a input?
How do I filter a YouTube URL like above picture? when Copy paste the URL It should automatically detect the YouTube and display like above.
can the process done through Laravel or Vue.js ?
Why does my vue project show this error?
Idea show me this :
Starting dev server... ERROR Failed to compile with 1 errors20:37:49
This relative module was not found:
- ./src/main.js in multi ./build/dev-client ./src/main.js
Listening at http://localhost:8088
How to access this.$root from VueJS component when inside a test
In VueJS 2.4, we can access root data from component thanks to this.$root, like in this JSFiddle:
https://jsfiddle.net/bjg2yL1u/1/
If you click on a button, you can see 'orange' displayed in the console, which is a root data, not owned by the todo-item who triggered it.
Now I am inside a Jasmine test. This test works/run/is green properly.
But the console.log inside todo-item component outputs 'undefined'.
How can I inject data to this.$root instance when inside a test ?
describe("TodoItem", function() { var sut; var message = {text:'word'} beforeEach(function() { var Constructor = Vue.extend(TodoItem); sut = new Constructor({ propsData: { todo: message, } }).$mount(); }); it("Should be able to reverse the given word", function() { // Given expect(sut.todo.text).toEqual('word'); expect($(sut.$el).find('li').text()).toEqual('word'); //When sut.reverseMessage(); // Bang !! problem here. 'undefined' is printed, because there is nothing attached to this.$root when inside a test // Then expect(sut.todo.text).toEqual('drow'); }); });Laravel\Vue - Request data empty on a production server
I have a component where I am uploading a video file, everything works fine on my local machine, and it used to work fine on the production server, until only recently after I have done some work and made changes that I saw that it doesn't work now on the production server:
I am using Vue v. 1.0.28, and this is the upload component:
<template> <div class="card-content col-md-10 col-md-offset-1"> <div v-if="!uploading"> <div class="col-md-12 Image-input__input-wrapper"> Upload video <input type="file" name="video" id="video" @change="fileInputChange" class="Image-input__input" accept="video/*"> </div> </div> <div class="alert alert-danger video-upload-alert" v-if="failed">Something went wrong. Please check the video format and try again. If you need any help please contact our <a>support service.</a></div> <div id="video-form"> <div class="alert alert-info" v-if="uploading && !failed && !uploadingComplete"> Please do not navigate away from this page, until the video has finished uploading. Your video will be available at <a href="{{ $root.url }}/videos/{{ uid }}" target="_blank">{{ $root.url }}/videos/{{ uid }}</a>, once uploaded. </div> <div class="alert alert-success" v-if="uploading && !failed && uploadingComplete"> Upload complete. Video is now processing. <a href="/videos">Go to your videos</a>. </div> <div class="progress" v-if="uploading && !failed && !uploadingComplete"> <div class="progress-bar" v-bind:style="{ width: fileProgress + '%' }"></div> </div> <div class="row"> <div class="col-md-12 form-group"> <label for="title" class="control-label">Title</label> <input type="text" class="form-control" v-model="title"> </div> <!-- <div class="col-md-12 form-group"> <label for="visibility" class="control-label">Visibility</label> <select class="form-control" v-model="visibility"> <option value="private">Private</option> <option value="unlisted">Unlisted</option> <option value="public">Public</option> </select> </div> --> </div> <div class="row"> <div class="col-md-12 form-group"> <label for="description" class="control-label">Description</label> <textarea class="form-control" v-model="description"></textarea> </div> </div> <div class="row"> <div class="col-md-12 form-group"> <button type="submit" class="btn btn-submit" @click.prevent="update">Save</button> </div> </div> <div class="row"> <div class="col-md-12 form-group"> <span class="help-block pull-right">{{ saveStatus }}</span> </div> </div> </div> </template> <script> function initialState (){ return { uid: null, uploading: false, uploadingComplete: false, failed: false, title: null, link: null, description: null, visibility: 'private', saveStatus: null, fileProgress: 0 } } export default { data: function (){ return initialState(); }, methods: { fileInputChange() { this.uploading = true; this.failed = false; this.file = document.getElementById('video').files[0]; var isVideo = this.isVideo(this.file.name.split('.').pop()); if (isVideo) { this.store().then(() => { var form = new FormData(); form.append('video', this.file); form.append('uid', this.uid); this.$http.post('/upload', form, { progress: (e) => { if (e.lengthComputable) { this.updateProgress(e) } } }).then(() => { this.uploadingComplete = true this.uploading = false }, () => { this.failed = true this.uploading = false }); }, () => { this.failed = true this.uploading = false }) } else { this.failed = true this.uploading = false } }, isVideo(extension) { switch (extension.toLowerCase()) { case 'm4v': case 'avi': case 'mpg': case 'mp4': case 'mp3': case 'mov': case 'wmv': case 'flv': return true; } return false; }, store() { return this.$http.post('/videos', { title: this.title, description: this.description, visibility: this.visibility, extension: this.file.name.split('.').pop() }).then((response) => { this.uid = response.json().data.uid; }); }, update() { this.saveStatus = 'Saving changes.'; return this.$http.put('/videos/' + this.uid, { link: this.link, title: this.title, description: this.description, visibility: this.visibility }).then((response) => { this.saveStatus = 'Changes saved.'; setTimeout(() => { this.saveStatus = null }, 3000) }, () => { this.saveStatus = 'Failed to save changes.'; }); }, updateProgress(e) { e.percent = (e.loaded / e.total) * 100; this.fileProgress = e.percent; }, } } </script>The problem is that on upload in my controller in the store function I am receiving empty request object on the production server, and then it fails to find the video:
class VideoUploadController extends Controller { public function index() { return view('video.upload'); } public function store(Request $request) { $player = $request->user()->player()->first(); $video = $player->videos()->where('uid', $request->uid)->firstOrFail(); $request->file('video')->move(storage_path() . '/uploads', $video->video_filename); $this->dispatch(new UploadVideo( $video->video_filename )); return response()->json(null, 200); } }I am not sure what is going on, since like I wrote it works fine on the local machine, and there I am sending a request that looks like this:
req: {uid: "1598efd62620bd", video: {}}
What is wrong and how can I fix this?
Axios interceptor doesn't intercept on page load
I am implementing JWT into my Vue application for authorization and I refresh my tokens once they are used.
I have used axios interceptors so I can intercept every request to my API backend and this seems to work on login etc... but once I refresh the page the request is made as normal using the last token.
The problem is the axios interceptors don't seem to work at this point, so once the token has been used I can't update it with the new one.
Here's how I'm setting my interceptors:-
window.axios.interceptors.request.use(function (config) { console.log("Sent request!"); return config; }, function (error) { console.log("Failed sending request!"); return Promise.reject(error); }); window.axios.interceptors.response.use(function (response) { console.log("Got headers:", response.headers); if (response.headers.hasOwnProperty('authorization')) { console.log("Got authorization:", response.headers.authorization); Store.auth.setToken(response.headers.authorization); } return response; }, function(err){ console.log("Got error", err); });I don't get any of the console.log's on page load.
I am setting my interceptors in the root app's beforeMount method. I've tried moving them to beforeCreate and I still get the same issue.
Resetting Vuex store state, properly
I have a Nuxt application with the following store / state setting:
const store = () => { return new Vuex.Store({ state: { user: { auth: { isLoggedIn: false }, subscription: { has_a_subscription: false }, current_check_in: {}, current_study_level: {} } }, getters, actions, mutations }) }I update the state via mutation upon login and also persist the data in localStorage and in a cookie. On Logout I'll clear localStorate and the cookies and also want to reset the state to its initial state:
import { setUser, unsetUser } from '~/utils/auth' var config = require('~/config.js').get(process.env.NODE_ENV) const actions = { nuxtServerInit ({ commit }, { req }) { // TODO }, async login ({ commit }, { payload, $axios }) { try { const { data } = await $axios.post(config.auth.LOGIN, payload) var user = _.pick(data, ['name', // etc]) user.auth.isLoggedIn = true commit('SET_USER', user) // Set the cookie setUser({ key: user.username, payload: user }) } catch (error) { if (error.response && error.response.status === 401) { throw new Error('Bad Credentials') } throw error } }, logout ({ commit }) { unsetUser() commit('CLEAR_STATE') } }I tried different approaches resetting the state to no avail:
try #1:
CLEAR_STATE: (state) => { console.log('resetting data...') var initialState = { auth: { isLoggedIn: false }, subscription: { has_a_subscription: false }, current_check_in: {}, current_study_level: {} } state.user = Object.assign({}, state.user, initialState) }try #2: Define functions to return the initial state(s):
CLEAR_STATE: (state) => { console.log('resetting data...') Vue.set(state, 'user', initialStates.user()) }try #3:
CLEAR_STATE: (state) => { console.log('resetting data...') Vue.set(state.user, 'auth', initialStates.auth()) Vue.set(state.user, 'subscription', initialStates.subscription()) Vue.set(state.user, 'current_check_in', initialStates.current_check_in()) Vue.set(state.user, 'current_study_level', initialStates.current_study_level()) }The mutation 'CLEAR_STORE' doesn't get recorded in vue dev tools even though the console log 'resetting data' appears. There must be something that I am missing here.
I am using the latest 1.0 release candidate of nuxt:
"@nuxtjs/axios": "^3.1.0", "@nuxtjs/component-cache": "^0.1.3", "@nuxtjs/pwa": "latest", "backpack-core": "^0.4.1", "body-parser": "^1.17.2", "es6-promise": "^4.1.1", "express": "^4.15.3", "firebase": "^4.2.0", "js-cookie": "^2.1.4", "jwt-decode": "^2.2.0", "nuxt": "^1.0.0-rc4", "vuelidate": "^0.5.0", "vuetify": "^0.14.0", "whatwg-fetch": "^2.0.3"Bind Styles After Ajax Call
On mounted(), I make an ajax call which pulls in div-specific data such as position on the screen. The problem is that my custom method to set v-bind:style from the ajax data gets run before ajax is finished, thus no data is there to pull from. What is the best way to set my style after ajax is done?
Ajax call returns something like this: [{name: 'table1', top: 10, left: 25},{name: 'table2', top: 30, left: 100}]
$(function() { var app = new Vue({ el: '#main', data: { tables: [] }, methods: { computeOffsets() { return { top: this.tables.top + 'px', left: this.tables.left+ 'px'} } }, mounted() { $.ajax({ method: 'POST', dataType: 'json', url: base_url + 'tables/getTables/' + event_id }).done(data => { console.log(data); this.tables = data; }); } }); }); .table { position: absolute; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script> <div id="main"> <div class='table' v-for="table in tables" v-bind:style="computeOffsets()"> {{table.name}} </div> </div>
Getting element that is created with vue2, using jQuery
I have couple of inputs which I created with v-for and I have structured them like this:
<input class="form-control" type="text" :id="'info[' + client + '][' + index + '][name]'"So, id of an element is for example info[1][1][name]. I can confirm it in inspector.
Now, I am trying to change it's value. The easiest way seemed jQuery to me, because I need to get field information from another component and write on this input (and I knew the client & index so I could $() easily).
As id of our element is info[1][1][name], I tried using $('#info[1][1][name]) in the console but I couldn't get it. Also tried $('body').find('#info[1][1][name]), but no luck either.
What am I doing wrong?
How can I use the axios.interceptor in a right way?
I use vue-cli and this is part of my main.js
import Vue from 'vue' import App from './App' import axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios, axios) Vue.config.productionTip = false new Vue({ el: '#app', template: '<App/>', components: { App } })In Vue's single File components' structure, I use axios to replace the ajax.
Vue.use(VueAxios, axios)It makes axios available in every SFC by referring (this.axios). But when I try to use axios.interceptor, I come across an annoying problem. I want to set axios.interceptor.request and axios.interceptor.reponse for the whole project. however, I can only use this.axios.interceptor.request in a Single File Component and it only work in this file. This is the part code of App.js.
methods: { // interceptor setAxiosInterceptor () { this.axios.interceptors.request.use(config => { this.cover = true return config }, error => Promise.reject(error) ) this.axios.interceptors.response.use(response => { this.cover = false return response }, error => { this.cover = false return Promise.reject(error) }) },I have to set this.axios.interceptor in every SFC. So how can I set the axios.interceptor for the whole project and make it available in every SFC.
Component based theming
I'm a front-end developer. I use my custom made CSS framework with sass. I have some jquery knowledge and a little javascript knowledge. I have heard a lot about angular, react, vue, ember etc. But I don't know how can I use them or how they are useful.
I try to explain my needs with some examples.
1- I use jquery ajax to upload and remove image. For this I need define input file and some javascript codes then style with css. For this I want to use something like below. And all html, css, javascript loads
<imageUpload></imageUpload>2- I have a nav section in my website. One in the header, one in the footer. They are some except some minor styles. I want to define default nav and have a option to override some values like below.
<myNav></myNav> <myNav place="footer></myNav>NOTE: All my codes are imaginary. I don't need and backend features. I'm going to use PHP for that. All I need front end things. (html, css, javascript, jquery, interaction, dom manipulation etc)
You don't have to recommend only one framework. I just need which one/ones are suitable for this job
How to pass global variable from parent to child in Vuejs?
I have a page called Profile.vue which is structured like this,
<style> </style> <template> <component-1></component-1> <component-2></component-3> <component-3></component-3> </template> <script> import component1 from '...../..' import component2 from '...../..' import component3 from '...../..' export default { name: 'profile', data(){ return{ pagename: 'Profile', mydata: 'This is my data' } } } </script>How do i make the data available in mydata, to all the components that I am importing,i.e, how can I pass data that would be available to all the components?
Update value in multidimensional array in Vue
I understand from the caveats portion of the Vue docs that updating a value in an array in the following manner will not work:
this.arr[idx] = newValand that one should use splice(). I am using a 2D array to store grid data, and I am having a difficult time updating the value when a cell in the grid is clicked.
Here is my template:
<tr v-for="(row, rowKey, index) in grid" :key="rowKey"> <th class="row-col-label" >{{rowKey+1}}</th> <td v-for="(col, colKey, index) in row" :key="colKey" @click="selectCell(rowKey, colKey)" :class="{'selected' : cellSelected(rowKey, colKey)}" > {{col}} </td> </tr>And here is the relevant code for the Vue component:
created () { this.initColHead() this.createSpreadSheet() }, data () { return { selected: '', grid: [], colHead: [' '], isSelected: false } }, methods: { initColHead () { this.colHead.push(...'ABC'.split('')) }, createSpreadSheet () { for (let i = 0; i <= 2; i++) { this.grid[i] = [] for (let j = 0; j <= 2; j++) { this.grid[i][j] = false } } }, selectCell (row, col) { this.isSelected = true console.log(`row ${row} col ${col}`) this.grid[row].splice(col, 1, true) for (let i = 0; i <= 2; i++) { for (let j = 0; j <= 2; j++) { console.log(this.grid[i][j]) } } }, cellSelected (row, col) { return (this.grid[row][col] === true) } }So I am attempting to add a true value to the cell that is click at the given row col locations provided in the my selectCell method. However, the data in my grid is not updated to reflect the newly added value. How exactly do I update values in a multidimensional array in Vue?