link1918 link1919 link1920 link1921 link1922 link1923 link1924 link1925 link1926 link1927 link1928 link1929 link1930 link1931 link1932 link1933 link1934 link1935 link1936 link1937 link1938 link1939 link1940 link1941 link1942 link1943 link1944 link1945 link1946 link1947 link1948 link1949 link1950 link1951 link1952 link1953 link1954 link1955 link1956 link1957 link1958 link1959 link1960 link1961 link1962 link1963 link1964 link1965 link1966 link1967 link1968 link1969 link1970 link1971 link1972 link1973 link1974 link1975 link1976 link1977 link1978 link1979 link1980 link1981 link1982 link1983 link1984 link1985 link1986 link1987 link1988 link1989 link1990 link1991 link1992 link1993 link1994 link1995 link1996 link1997 link1998 link1999 link2000 link2001 link2002 link2003 link2004 link2005 link2006 link2007 link2008 link2009 link2010 link2011 link2012 link2013 link2014 link2015 link2016 link2017 link2018 link2019 link2020 link2021 link2022 link2023 link2024 link2025 link2026 link2027 link2028 link2029 link2030 link2031 link2032 link2033 link2034 link2035 link2036 link2037 link2038 link2039 link2040 link2041 link2042 link2043 link2044 link2045 link2046 link2047 link2048 link2049 link2050 link2051 link2052 link2053 link2054

[Vue.js] Vue data variable not updating after language change

there is a data variable as follows:

data(){
return {
amount: {
active: false,
name: this.$i18n.t(‘key_name’),
value: this.$i18n.t(‘key_value’)
}
}
}

The data variable is using localized string. The issue is that, when I change the language from a dropdown, the amount variable is not updating until any other event occurs. I believe this has something to do with the $nextTick().

But not sure how to handle this properly as to have the changes reflected immediately in the amount variable.

I can’t make it as a computed property as I’ve to assign values to this variable at a later point.

like this:

this.amount.active = true

How can I solve this?

Solution :

It’s hard to tell how you use vue.js i18n, but you can use a watcher as it is stated in the docs and watch for the global i18n.locale object, something like:

<script>
export default {
name: ‘app’,
data () {
return {
amount: {
active: false,
name: this.$i18n.t(‘key_name’),
value: this.$i18n.t(‘key_value’)
}
}
},
watch: {
this.$i18n.locale (val) {
this.amount.active = true
}
}
}
</script>

Depends how it’s configured in the project.

[Vue.js] Vue Prop undefined for just the first item in v-for loop using a component

there is a component that looks like this.

#this is the <review-stars> component
export default {
props: [‘NumStars’, ‘RecipeName’],

data() {
return{
stars: this.NumStars,
recipe: this.RecipeName,
}
},

mounted () {
},
}

It has a section as well, but things are find there.

I then have my html page that looks like this.

<recipe-selects inline-template>
<div>
<table class=’table table-striped’>
<thead>
</thead>
<tbody>

<tr v-for=”(item, index) in recipes” :key=”index”>

<td class=””><a v-bind:href=”‘/recipe/‘+item.id+’/view’” v-text=”item.title”></a></td>
<td>

@{item.overall_star}
<review-stars :num-stars=”item.overall_star” :recipe-name=”item.title” >
</review-stars>
</td>
</tr>
</tbody>
</table>

</div>
</recipe-selects>

there is a component attached to and that works fine. It is an ajax call that loads the data for the v-for and I get a listing of recipes back. It is an inline component.

But, then there is another component that attaches to where I try to bind some props and pass them to my component I showed above.

When the v-for loop runs, I get a list of all the recipes. I also get a list of the ‘review-stars’ appropriately.

EXCEPT for the very first item in the for loop.

Here is vue.js Dev tools showing the first created ReviewStars instances shows data as undefined.
But in this you see that the second (and any further rows, but I limited it here to just 2 results) work exactly as expected.

Both show that the actual props get defined and picked up. But the props are only passed to the data (stars and recipe) from the second v-for loop and onwards.

What am I missing to assign the data (stars and recipe) in the FIRST v-for loop?

Solution :

The props are not there yet to populate the values in data. You have to wait for the created hook for everything to be ready and then you can use the values from props. You can use them directly from props. The only reason to duplicate them in data is if they are modified in this component.

export default {
props: [‘NumStars’, ‘RecipeName’],
data() {
return{
stars: null,
recipe: null,
}
},
created () {
this.stars = this.NumStars
this.recipe = this.RecipeName
},
}

[Vue.js] How to ignore custom elements in VuePress to avoid the Unknown custom element error?

when creating documentation for a W3C web components library (Vanilla JavaScript) using VuePress. However, my “custom” web components are generating an error due to VuePress trying to “recognize” them as vue.js components the very first time the page loads.

Once the page is loaded my web components work as expected, but the error is there anyway.

This is the error when getting:

vue.runtime.esm.js?2b0e:619 [vue.js warn]: Unknown custom element: <nova-timeline> - did you register the component correctly? For recursive components, make sure to provide the “name” option.

found in

-–> <TimeLineWrapper> at docs/.vuepress/components/TimeLineWrapper.vue

there is created the following structure related to Vuepress

.
docs
.vuepress
components
TimeLineWrapper.vue
config.js
theme
README.md
components
README.md
Timeline.md

And this is part of my code:

// docs/.vuepress/components/TimeLineWrapper.vue
<template>
<nova-timeline ref=”timeline”></nova-timeline>
</template>
<script>
import timeLineJson from “./data/TimeLineData”;

export default {
data() {
return {
timeLineJson: timeLineJson
};
},
mounted() {
this.$refs.timeline.data = this.timeLineJson.data;
this.$refs.timeline.configuration = this.timeLineJson.configuration;
}
};
</script>

// This is my W3C web component:
<nova-timeline ref=”timeline”></nova-timeline>

What I like to know is how to “ignore custom components”, I mean where or how to do this kind of configuration using the VuePress way.

Vue.config.ignoredElements = [
// Use a `RegExp` to ignore all elements that start with “nova-“
// 2.5+ only
/^nova-/
]

https://vuejs.org/v2/api/#ignoredElements

Thanks in advance.

Solution :

I finally manage to find how to add my ignored elements,

1) Create a file named enhanceApp.js in docs/.vuepress/theme

2) Place this content inside of it:

// https://vuepress.vuejs.org/guide/custom-themes.html#app-level-enhancements
export default ({ Vue, options, router, siteData }) => {
Vue.config.ignoredElements = [
// Use a `RegExp` to ignore all elements that start with “nova-“
// 2.5+ only
/^nova-/
];
}

Now, the error will disappear since vue.js will ignore our custom web components.

[Vue.js] 405 Error & CORS when making an api request on localhost

I’m trying to pull data from a weather API on my localhost environment and I’m getting a 405 Error(Method not allowed) as well as “has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.” I’ve config’d my headers and can’t figure out what i’m doing wrong. It works fine on live but obviously that’s not a convenient way doing it.

I’ve tried using axios.get as well as axios.post.

var config = {
headers: {‘Access-Control-Allow-Origin’: ‘*‘}
};
getWeather: function (){
axios.get(‘http://api.openweathermap.org/data/2.5/forecast?id='+ city + ‘&appid=’+ apiKey, config).then((res) => {this.weather = res.data});
}

Solution :

Hope adding below package will help

use this https://github.com/barryvdh/laravel-cors

Installation :

composer require barryvdh/laravel-cors

Service provider :

Add this Barryvdh\Cors\ServiceProvider::class, in config/app.php

To allow CORS for all the routes, add the HandleCors middleware in the $middleware property of app/Http/Kernel.php class:

protected $middleware = [
\Barryvdh\Cors\HandleCors::class,
// …
];

NOTE: make sure to place it before all middlewares

If it’s for specific middleware, on our case, it will be api

protected $middlewareGroups = [
‘web’ => [
// …
],

‘api’ => [
\Barryvdh\Cors\HandleCors::class,
‘throttle:60,1’,
‘bindings’,
],

];

NOTE: make sure to place it before all middlewares

Publish the config :

php artisan vendor:publish –provider=”Barryvdh\Cors\ServiceProvider”

[Vue.js] native script equivalent to window.localStorage with vuejs app

Starting out on a new app of reasonable size, VueJS/typescript is the frontend choice. Currently persisting the data into localstorage with https://www.npmjs.com/package/vuex-persist

Before venturing much further into the build, i know this app will also need to be a mobile app, native script + vuejs looks like a nice combo.. but my question.

What is the best way to replicate localStorage in a mobile app with native script?

About 5 years i built my last mobile app for ios, I used titanium with SQLite. SQLite was ok, not blazing fast but it was good enough for what i needed. Is SQLite still the way to go for mobile apps?

Solution :

There is nativescript-localstorage plugin which mimics localStorage on Browser by saving the key pairs to a JSON file.

There is also nativescript-sqlite if you prefer to go with SQLite.

[Vue.js] What is the difference between 'data ', 'data ()' and 'data()' in Vue.js

In Vue.js docs I’ve found two ways of defining data so far: data: {} and data() { return; }.

data: {
defaultLayout: ‘default’
}

data() {
return {
defaultLayout: ‘default’
}
}

So far, I don’t have any clue about third ways: data: () => ({}). How it makes differ from above two’s.

data: () => ({
defaultLayout: ‘default’
})

Solution :

Inside an object literal,

data() {
return {
defaultLayout: ‘default’
}
}

is a shorthand for

data: function() {
return {
defaultLayout: ‘default’
}
}

which you can write with an arrow function:

data: () => ({
defaultLayout: ‘default’
})

Solution 2:

Arrow functions are shorthands for returning a value. If you write this code:

() => “aaa”

It returns “aaa” string. So there is a hidden return statement there. Keeping this in my if we look at:

data: () => ({
defaultLayout: ‘default’
})

Returns an object which has “defaultLayout” property. Let’s look at the first code sample.

data() {
return {
defaultLayout: ‘default’
}
}

is equal to:

data: function() {
return {
defaultLayout: ‘default’
}
}

So second and third code samples are almost equal. There is just one difference, arrow functions have lexical “this”.

the first sample is a bad practice. You can read it about it here.

[Vue.js] Vue.js - Import and export dynamically

I’m working on a nuxt.js project and need to import multiple components from a folder on a single line

currently

import ButtonStyled from ‘@/components/atoms/ButtonStyled.vue’
import TextLead from ‘@/components/atoms/TextLead.vue’
import InputSearch from ‘@/components/atoms/InputSearch.vue’

what I need to do

import {
ButtonStyled,
TextLead,
InputSearch
} from ‘@/components/atoms’

so I thought I’d create an index.js

import ButtonStyled from ‘./ButtonStyled.vue’
import TextLead from ‘./TextLead.vue’
import InputSearch from ‘./InputSearch.vue’

export default {
ButtonStyled,
TextLead,
InputSearch
}

it works, but the problem is that every component created or deleted the index.js needs to be changed, so I need to import and export dynamically

Does anyone have any ideas?

NOTE: i can not import into atoms and then destructuring the components, I need to import the components as i mention, in a single line, single statement, cleanly and clearly,

The closest I got was the following

I create an index.js in the ‘@/components/atoms/‘ directory with the code below

const req = require.context (‘./‘, true, /\.vue$/)

const components = {}

req.keys (). forEach (fileName => {
const componentName = fileName.replace (/^.+\/ ([^ /] +) \ .vue.js /, ‘$ 1’)
components [componentName] = req (fileName) .default
})

and then export the component object

export default components

however, exporting in this way, I can only use the components to import and then de-structure

import atoms from “@/components/atoms”
const {ButtonStyled} = atoms;

But that’s not what I want.

if in index.js I export as follows

export const {ButtonStyled, TextLead, InputSearch} = components

I get the result I need, which is import into a single statement

import {ButtonStyled} from ‘@/components/atoms’

but the problem persists, there is exported the components in a static way, manually, I need to export 100% dynamic, if there was a way to dynamically define the name of the variables / components to be exported, or any other way so I could the way I need it in a single statement

Solution :

Have you considered global registration of components that are commonly reused throughout the application?

https://vuejs.org/v2/guide/components-registration.html#Automatic-Global-Registration-of-Base-Components

Heres an example of the code you might use to globally import base components in the apps entry file (e.g. src/main.js):

import vue.js from ‘vue’
import upperFirst from ‘lodash/upperFirst’
import camelCase from ‘lodash/camelCase’

const requireComponent = require.context(
// The relative path of the components folder
‘./components’,
// Whether or not to look in subfolders
false,
// The regular expression used to match base component filenames
/Base[A-Z]\w+\.(vue|js)$/
)

requireComponent.keys().forEach(fileName => {
// Get component config
const componentConfig = requireComponent(fileName)

// Get PascalCase name of component
const componentName = upperFirst(
camelCase(
// Gets the file name regardless of folder depth
fileName
.split(‘/‘)
.pop()
.replace(/\.\w+$/, ‘’)
)
)

// Register component globally
Vue.component(
componentName,
// Look for the component options on `.default`, which will
// exist if the component was exported with `export default`,
// otherwise fall back to module’s root.
componentConfig.default || componentConfig
)
})

Simply move all the components to a folder that makes sense ex. ‘./components/base

Now you can use the kabab case or camel case version of the components anywhere in the app.

[Vue.js] Exposing variables from main.js to other scripts in a vue-cli project

I need to access the vue.js instance, declared inside main.js of my vue-cli project, from outside the webpack-generated .js file. In main.js, I have:

var vm = new Vue({
store,
render: h => h(App)
}).$mount(‘#app’);

However, because webpack wraps this code in a function and minifies it, the vm variable is never accessible from outside the script. How can I fix that and ensure the vm variable can be accessed from other scripts?

All webpack settings are the defaults provided by vue-cli.

Solution :

You could export the vue.js instance and import it in the other scripts.

export const vm = new Vue({
store,
render: h => h(App)
}).$mount(‘#app’);

To access it in the other scripts, simply use

import { vm } from ‘path/main.js’

Solution 2:

You can put it on window

window.myComponent = new Vue({
store,
render: h => h(App)
}).$mount(‘#app’);

[Vue.js] In Vue.js, why isn't my computed property working

In the following code:

new Vue({
el: ‘#app’,
computed: {
myMessage: function() {
return “hello”;
}
},
data: {
message: this.myMessage
},
mounted: function() {
console.log(this.myMessage);
}
})
<script src=”https://unpkg.com/vue"></script>

<div id=”app”>
<p>{ message }</p>
</div>

https://jsfiddle.net/hk49eL38/

if I replace:

this.myMessage with a string (eg “Hello world”), it renders correctly.

But when I use this.myMessage, no text is rendered.

Why is this?

Solution :

The problem is that you are trying to use the computed property as the initial value of the message data property.

When the data function is called internally by Vue, the computed properties haven’t been evaluated yet, this is done very early, before the created hook.

If you try to log the value of the computed property in the beforeCreated hook (the first life-cycle hook) instead of the mounted as in the example, you will see that it is undefined.

See the component life-cycle:

(*) Diagram cropped for brevity

Computed properties are evaluated in the “Init injections & reactivity” step in the above diagram.

Computed property values cannot be used as the initial value of a property of data, and normally they depend on data property values and other external and reactive values (e.g. Vuex getters, vue.js router parameters, etc).

Solution 2:

You shouldn’t use this before writing myMessage, as VueJS doesn’t work like that. It already considers everything in this context. You should do it like this:

<script src=”https://unpkg.com/vue"></script>

<div id=”app”>
<p>{ myMessage }</p>
</div>

Solution 3:

Try setting the value of myMesssage to message when component is mounted.

mounted: function() {
this.message = this.myMessage
}

Solution 4:

Try to change the data message in the computed my message

[Vue.js] Vue 'data' not getting changed through input tag in html

when trying to get the HTML input to be reflected in the vue.js dev tool panel and in the console but none of them are working.

my blade file contains this code.

<!DOCTYPE html>
<html lang=”en” dir=”ltr”>
<head>
<meta charset=”utf-8”>
<meta name=”csrf-token” content=”{ csrf_token() }”>
<link rel=”stylesheet” href=”{ asset(‘css/app.css’) }”>
<title>Chat Room</title>

</head>
<body>
<div class=”container” id=”app”>
<div class=”row”>
<ul class=”list-group offset-4 col-4”>
<li class=”list-group-item active”>Chat Room</li>
<input type=”text” class=”form-control” placeholder=”Type the
message here” v-model=”text” @keyup=’send’></input>
</ul>
</div>
</div>
{– <script src=”{ asset(‘js/app.js’) }”></script> –}
</body>
</html>

The app.js is like this.

require(‘./bootstrap’);

window.vue.js = require(‘vue’);

Vue.component(‘message’, require(‘./components/message.vue’));

const app = new Vue({
el: ‘#app’,
data: {
text:’’
},
method:{
send(){
console.log(this.message);
}
}
});

The thing is when not getting any error but the binding is also not working. when looking for the input text in the html to be displayed in the console and vue.js panel data array.

Solution :

Layout.app already contains html head and body tags isn’t it?
At this time you are putting a whole new page inside the page

So it won’t work cause the first div#app is in the app.blade.php

EDIT : plus the script is commented with blade line comment markup