link2877 link2878 link2879 link2880 link2881 link2882 link2883 link2884 link2885 link2886 link2887 link2888 link2889 link2890 link2891 link2892 link2893 link2894 link2895 link2896 link2897 link2898 link2899 link2900 link2901 link2902 link2903 link2904 link2905 link2906 link2907 link2908 link2909 link2910 link2911 link2912 link2913 link2914 link2915 link2916 link2917 link2918 link2919 link2920 link2921 link2922 link2923 link2924 link2925 link2926 link2927 link2928 link2929 link2930 link2931 link2932 link2933 link2934 link2935 link2936 link2937 link2938 link2939 link2940 link2941 link2942 link2943 link2944 link2945 link2946 link2947 link2948 link2949 link2950 link2951 link2952 link2953 link2954 link2955 link2956 link2957 link2958 link2959 link2960 link2961 link2962 link2963 link2964 link2965 link2966 link2967 link2968 link2969 link2970 link2971 link2972 link2973 link2974 link2975 link2976 link2977 link2978 link2979 link2980 link2981 link2982 link2983 link2984 link2985 link2986 link2987 link2988 link2989 link2990 link2991 link2992 link2993 link2994 link2995 link2996 link2997 link2998 link2999 link3000 link3001 link3002 link3003 link3004 link3005 link3006 link3007 link3008 link3009 link3010 link3011 link3012 link3013

[Vue.js] Pass Props component to root Instance

I’m super newbie in vuejs. I don’t know how to pass props component to root instance
Here is my code.

component (Tesvue.vue)

<template>
<label class=”col-md-2 control-label”>{name}</label>
</template>

<script>
export default {
props: [‘name’]
}
</script>

Root (app.js)

window.vue.js = require(‘vue’);
import tesvue.js from ‘./components/Tesvue.vue’;

var vm = new Vue({
el: ‘#app’,
components: {
tesvue
},
data:{
getname: ‘’
}
});

blade file

<div class=”” id=”app”>
<tesvue.js name=”{$model->name}”></tesvue>
</div>

The scenario is, im fetching data from laravel controller to blade element, then vue.js js can access it. This is like pass php variable to vuejs.
I know this can be done with Php-vars-to-javascript plugin, or i can simply use it inline. like this
var name = {name}

but do that in vuejs way (props).

So how to pass props data to root instance. How ‘getname’ can get props ‘name’
Thanks, sorry my bad english.

Solution :

A component can not directly pass data back to its parent. This is only possible via events. So for this to work you’d have to emit an event from the child component as soon as its ready and have to listen for that event. In the case its like this:

Component (Tesvue.vue)

<template>
<label class=”col-md-2 control-label”>{name}</label>
</template>

<script>
export default {
props: [‘name’],
mounted() {
this.$emit(‘setname’, this.name);
}
}
</script>

Root (app.js)

window.vue.js = require(‘vue’);
import tesvue.js from ‘./components/Tesvue.vue’;

var vm = new Vue({
el: ‘#app’,
components: {
tesvue
},
data: {
getname: ‘’
}
methods: {
changeName(name) {
this.getname = name;
}
}
});

blade file

<div class=”” id=”app”>
<tesvue.js name=”{$model->name}” @setname=”changeName”></tesvue>

<!– getname got set through changeName event –>
<span v-text=”getname”></span>
</div>

Solution 2:

I found the solution

<template>
<label class=”col-md-2 control-label”>{name}</label>
</template>

<script>
export default {
props: [‘name’],
mounted: function() {
this.$root.getname = this.name;
}
}
</script>

check this out
https://jsfiddle.net/mtL99x5t/

but many thanks for @Reduxxx for answer my newbie question.

Solution 3:

Here’s nice solution using dataset:

HTML:

<div id=”app” data-name=”dataname”>

Component (Testvue.vue):

<template>
<label class=”col-md-2 control-label”>{name}</label>
</template>

Root Instance (App.js)

const root_element = document.getElementById(‘app’);

new Vue({
el: root_element,
propsData: { name: root_element.dataset.name }
});

See more about propsData in the docs.

If you want to use multiple dataset at once, you can assign an object using spread operator like this: (if you’re using Babel and have the object-rest-spread plugin)

const root_element = document.getElementById(‘app’);

new Vue({
el: root_element,
propsData: { …root_element.dataset }
});

Or, simply use ES6 method if you have not used Babel: (Object.assign())

propsData: Object.assign({},root_element.dataset)

So, if you have defined multiple dataset in the html like this:

<div id=”app”
data-name=”dataname”
data-another=”anotherdata”
data-anything-else=”anydata”>

You can expose props like this:

export default {
// …
props: [‘name’, ‘another’, ‘anythingElse’],
// …
};

Solution 4:

There are some ways to pass data from child to the parent.The best and acceptable are using Vuex Store and emit an event.

If you want to emit an event from child you can call a method to do that:

callThisMethod () {
this.$emit(‘nameOfEventYouWantToListen’, dataToPass)
}

Then you can listen to this event in parent component in which you have import the component

<ImportedComponent @nameOfEventYouWantToListen=”callFunctionInParentHere” />

Alternatively if you want to use Vuex then go and create a property in state of store,also a getter to get that property from state and a mutation to change the value of property located in state.

Then in parent component use a getter to get the property in state and in child component commit a mutation (would be great if you include actions in whole proccess tho) to change the property in state.

[Vue.js] How to create anchor tags with Vue Router

when creating a small vue.js webapp, to create an anchor tag in this.

there is given an id to one of the div I wanted to have anchor tags like this:

<div id=”for-home”>
….
</div>

And here is my router configuration:

export default new Router({
abstract: true,
mode: ‘history’,
scrollBehavior: () => ({ y: 0 }),
routes: [
{ path: ‘/‘, component: abcView}
]
})

But with this anchor tags are sometimes working and sometimes not working, Have I missed something in this?

Solution :

I believe you are asking about jumping directly to a particular area of page, by navigating to an anchor tag like #section-3 within the page.

For this to work, you need to modify the scrollBehavior function as follows:

new VueRouter({
mode: ‘history’,
scrollBehavior: function(to, from, savedPosition) {
if (to.hash) {
return {selector: to.hash}
} else {
return { x: 0, y: 0 }
}
},
routes: [
{path: ‘/‘, component: abcView},
// the routes
]
});

Ref: https://router.vuejs.org/guide/advanced/scroll-behavior.html#async-scrolling

I attempted creating a jsFiddle example but it is not working because of mode:’history’. If you copy the code and run locally, you will see how it works: https://jsfiddle.net/mani04/gucLhzaL/

By returning {selector: to.hash} in scrollBehavior, you will pass the anchor tag hash to the next route, which will navigate to the relevant section (marked using id) in that route.

Solution 2:

there is just came across this problem too and I thought there is a little space to optimize the page swap. In my case I’d like to make a smooth transition instead of “jumping arround”. I’ve already required in jQuery as alias for $.

Here is my Router Setup for the smooth animation, feel free to modify the lines to the needs accordingly. This code could been made cleaner but should be fine enough to show you the working idea.

// Register Router and Paths
const router = new VueRouter({
mode: ‘history’,
routes : [
{ path: ‘/aboutme/‘, component: index, name:’me.index’},
{ path: ‘/aboutme/cv’, component: cv, name:’me.cv’ }
],

// Build smooth transition logic with $
scrollBehavior (to, from, savedPosition) {
if (to.hash) {
return $(‘html,body’).stop().animate({scrollTop: $(to.hash).offset().top }, 1000);
} else {
return $(‘html,body’).stop().animate({scrollTop: 0 }, 500);
}
}
})

Side Question on my side: Do we have to return anything? I don’t have any trouble with or without returning due the jQuery Animation is handling the page scroll.

regards Gkiokan

Solution 3:

If you need to make animated scrollTo I use package vue-scrollTo: it’s very easy to setup.

Examples with docs and code can be found here: https://rigor789.github.io/vue-scrollto/

[Vue.js] How to handle drag and drop lists in mongodb/express?

I’m building a kanban board like spa with user boards that contain lists, and lists that contain cards all with drag and drop functionality using vue.js in front-end and express.js with mongoose in back-end.

I’m currently stuck on how to set up my models and sorting correctly.

Could anyone give me an example of a 3 simple mongoose models for a board, a list and a card that would work for a drag and drop functionality for lists and cards, together with sorting, routes would be awesome too?

I’m completely lost if I should use embedding or referencing, I’ve tried both ways but it doesn’t seem right.

Solution :

The decision for embedding vs referencing is often influenced by the way you want to query a data.
It is also an interesting question if cards would also contain discussions. (<- but that is another discussion) because it would bring another nesting level.

What about

var schema = new mongoose.Schema({bucket:’string’, position:’number’, title: ‘string’, body: ‘string’,isDone:’boolean’ });
var card = mongoose.model(‘Card’, schema);

the board would be all cards grouped by bucket and ordered by position within the bucket. (For Grouping it is recommended to use the aggregate function).

Dragging within a bucket (changing) the position would be to update the positions of the cards. Moving the cards between buckets would be to update the bucket field.

When you look at trello I think they worked with websockets which pushes changes to the clients and the client reacts to the updates.

This would mean a total different model. So, the server contains all changes for a board. So you would need to model all changes as commands/events. “CARD_CREATED”, CARD_MOVED_TO_BUCKET with its corresponding payload. With this, you would be able to push changes to the server and back to the client. You want to look at eventsourcing, cqrs, redux, to get more information about storing the state as a series of changes. Think about the bank account. The total is an aggregated result of all debits and credits.

So while the first approach will work for you, the second one could be interesting to look into it.

Hope that helps.

[Vue.js] Dynamic Vue Import from a subfolder

when trying to import all .vue.js files in a certain subfolder into another component. I know about Global registration of Base components but this does not seem to help me here.

Let’s say there is default vue.js component (not the main one) with something like this:

export default {
components: {
red: () => import(‘./panes/red’),
},
data() {
return {
current: false,
};
},

and my file structure is something like:

/src
- main.js
- main.vue
-- components/
-- panes/
-– /red.vue
-– /green.vue
-– /blue.vue
-- SubMain.vue

when trying to dynamically create the components object for the SubMain.vue.js folder.

So I try something like this in SubMain.vue:

import myComponents from ‘./src/components/panes’;

components: Object.keys(myComponents).reduce((obj, name) => {
return Object.assign(obj, { [name]: () => import(myComponents[name]) })
}, {}),

But eslint is giving me errors about Missing file extension and Unable to resolve path to module on the myComponents variable. Yes, I double checked my path and tried other paths. Nothing. when using the vue.js CLI 3 project.

Solution :

If you’re using Webpack, you can use require.context:

import _kebabCase from lodash/kebabCase

const components = require.context(‘src/panes’, true)

components.keys().map(component => {
// turn ‘./ComponentName.vue’ into ‘component-name’
const componentName = _kebabCase(
component.replace(/^\.\//, ‘’).replace(/\.vue$/, ‘’)
)
// register new component globally
Vue.component(componentName, components(component))
})

Solution 2:

I don’t think you can import multiple components that way without an index file that aggregates the component import/exports for you. See Import multiple components in vue.js using ES6 syntax doesn’t work

[Vue.js] Vue display unescaped html

How can I manage to get html interpreted inside a mustache binding? At the moment the break (<br />) is just displayed/escaped.

Small vue.js app

var logapp = new Vue({
el: ‘#logapp’,
data: {
title: ‘Logs’,
logs: [
{ status: true, type: ‘Import’, desc: ‘Learn<br />JavaScript’, date: ‘11.11.2015’, id: 1 },
{ status: true, type: ‘Import’, desc: ‘Learn<br />JavaScript’, date: ‘11.11.2015’, id: 1 }
]
}
})

And here is the template

<div id=”logapp”>
<table>
<tbody>
<tr v-repeat=”logs”>
<td>{fail}</td>
<td>{type}</td>
<td>{description}</td>
<td>{stamp}</td>
<td>{id}</td>
</tr>
</tbody>
</table>
</div>

Solution :

Starting with Vue2, the triple braces were deprecated, you are to use v-html.

<div v-html=”task.html_content”> </div>

It is unclear from the documentation link as to what we are supposed to place inside v-html, the variables goes inside v-html.

Also, v-html works only with <div> or <span> but not with <template>.

If you want to see this live in an app, click here.

Solution 2:

You can use the directive v-html to show it.
like this:

<td v-html=”desc”></td>

Solution 3:

You can read that here

If you use

{<br />}

it’ll be escaped. If you want raw html, you gotta use

NaN

EDIT (Feb 5 2017): As @hitautodestruct points out, in vue.js 2 you should use v-html instead of triple curly braces.

Solution 4:

vue.js by default ships with the v-html directive to show it, you bind it onto the element itself rather than using the normal moustache binding for string variables.

So for the specific example you would need:

<div id=”logapp”>
<table>
<tbody>
<tr v-repeat=”logs”>
<td v-html=”fail”></td>
<td v-html=”type”></td>
<td v-html=”description”></td>
<td v-html=”stamp”></td>
<td v-html=”id”></td>
</tr>
</tbody>
</table>
</div>

[Vue.js] Preferred way of using Bootstrap in Webpack

Greetings one and all,

there is been playing around with Bootstrap for Webpack, but I’m at the point of tearing my hair out. there is literally gone through loads of blog articles and they either use the 7 months outdated ‘bootstrap-webpack’ plugin (which, surprisingly does not work out of the box) or.. They include the Bootstrap files through import ‘node_modules/*/bootstrap/css/bootstrap.css’.

Surely, there must be a cleaner and more efficient way of going about this?

This is my current webpack.config.js file:

var webpack = require(‘webpack’);
var ExtractTextPlugin = require(‘extract-text-webpack-plugin’);
var autoprefixer = require(‘autoprefixer’);
var path = require(‘path’);

module.exports = {
entry: {
app: path.resolve(__dirname, ‘src/js/main.js’)
},
module: {
loaders: [{
test: /\.js[x]?$/,
loaders: [‘babel-loader?presets[]=es2015&presets[]=react’],
exclude: /(node_modules|bower_components)/
}, {
test: /\.css$/,
loaders: [‘style’, ‘css’]
}, {
test: /\.scss$/,
loaders: [‘style’, ‘css’, ‘postcss’, ‘sass’]
}, {
test: /\.sass$/,
loader: ‘style!css!sass?sourceMap’
},{
test: /\.less$/,
loaders: [‘style’, ‘css’, ‘less’]
}, {
test: /\.woff$/,
loader: “url-loader?limit=10000&mimetype=application/font-woff&name=[path][name].[ext]“
}, {
test: /\.woff2$/,
loader: “url-loader?limit=10000&mimetype=application/font-woff2&name=[path][name].[ext]“
}, {
test: /\.(eot|ttf|svg|gif|png)$/,
loader: “file-loader”
}]
},
output: {
path: path.resolve(__dirname, ‘dist’),
filename: ‘/js/bundle.js’,
sourceMapFilename: ‘/js/bundle.map’,
publicPath: ‘/‘
},
plugins: [
new ExtractTextPlugin(‘style.css’)
],
postcss: [
autoprefixer({
browsers: [‘last 2 versions’]
})
],
resolve: {
extensions: [‘’, ‘.js’, ‘.sass’],
modulesDirectories: [‘src’, ‘node_modules’]
},
devServer: {
inline: true,
contentBase: ‘./dist’
}
};

I could go and require(‘bootstrap’) (with some way of getting jQuery in it to work), but.. I’m curious to what you all think and do.

Thanks in advance :)

Solution :

when not sure if this is the best way, but following work for me well with vue.js webapp. You can see the working code here.

there is included files required by bootstrap in index.html like this:

<head>
<meta charset=”utf-8”>
<title>Hey</title>
<meta name=”viewport” content=”initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui”>
<link rel=”stylesheet” href=”/static/bootstrap.css” type=”text/css”>

<script src=”//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js”></script>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/tether/1.3.7/js/tether.min.js" integrity=”sha384-XTs3FgkjiBgo8qjEjBk0tGmf3wPrWtA6coPfQDfFEY8AnYJwjalXCiosYRBIBZX8” crossorigin=”anonymous”></script>
<script href=”/static/bootstrap.js”></script>
</head>

And this works, you can execute the repo. Why I went this way was I had to customise some config in bootstrap so I had to change the variables file and build the code of bootstrap which outputted me bootstrap.js and bootstrap.cssfiles, which when using here.

There is an alternative way suggested here by using the npm package and a webpack customisation.

First install bootstrap in the project:

npm install bootstrap@4.0.0-alpha.5

And make sure you can use sass-loader in the components:

npm install sass-loader node-sass –save-dev

now go to the webpack config file and add a sassLoader object with the following:

sassLoader: {
includePaths: [
path.resolve(projectRoot, ‘node_modules/bootstrap/scss/‘),
],
},

projectRoot should just point to where you can navigate to node_packages from, in my case this is: path.resolve(__dirname, ‘../‘)

Now you can use bootstrap directly in the .vue.js files and webpack will compile it for you when you add the following:

<style lang=”scss”>
@import “bootstrap”;
</style>

Solution 2:

I highly recommend using bootstrap-loader. You add a config file (.bootstraprc in the root folder) where you can exclude the bootstrap elements you don’t want and tell where the variables.scss and bootstrap.overrides.scss are. Define you SCSS variables, do the overrides, add the webpack entry and get on with the life.

[Vue.js] How can I handle a custom child event, emitted via this.$emit, in a parent component, within the <script> portion of the .vue file?

We are using vue.js and typescript, so our .vue.js files are organized essentially identically to this blogpost.

there is a child component emitting the custom event changeType. I would like to invoke a function on the parent component upon this event being emitted.

childComponent.vue

<template>
<div>
<span @click=”changeType(‘test’)”></span>
</div>
</template>
<script lang=”ts”>
import { Component, Prop, vue.js } from ‘vue-property-decorator’;

@Component
export default class ChildComponent extends vue.js {
@Prop(
{
default: ‘notTest’,
validator: (type) => {
return [
‘test’,
‘notTest’,
].indexOf(type) > -1;
},
},
)
currentType!: string;

changeType(currentType = ‘notTest’) {
this.$emit(‘changeType’, currentType);
}
}
</script>

Now, I’m unsure what to put in my parentComponent.vue.js file, which has <childComponent /> in its template area.

The vue.js documentation only addresses the handling of child events within the <template> area of a file, using v-on:

<blog-post

v-on:enlarge-text=”postFontSize += 0.1”
\></blog-post>

So, I suppose, do I need to have something like:

parentComponent.vue

<template>
<childComponent v-on:changeType=”handleChangeType” />
</template>

Or is there some way to do it in the <script> tag area only? Research has been made more difficult by the use of the class + typescript syntax. I was having some goes at things like this.$on but typescript did not like that at all, or perhaps I was putting it in the wrong section of the class (perhaps it belongs in the constructor or similar?)

I come from a Backbone background, so I was hoping for something like a onChangeType method added directly to the parent component would automatically handle the event, though perhaps that is old school and there’s newer better ways.

How can I handle a child component event within the tags of a parent component in vue? Is it possible without v-on within the template? Am I misunderstanding the “right” way to do this?

Solution :

You can add an event listener to a child component via the $on method, which you mentioned.

First, you’ll need to add a ref to the child component in the template:

<childComponent ref=”child”/>

Then, in the mounted hook, you’ll add the listener like so:

mounted() {
this.$refs.child.$on(‘changeType’, this.handleChangeType);
}

[Vue.js] VueJS , LoDash debounce watch on entire form

I’m trying to get LoDash debounce to work to trigger an event when a user stops typing on a form.

Something similar to this guide

Except to apply it to the entire form/model properties.

At the moment the debounce never fires.

Example JS Fiddle

JS

new Vue({
el: “#app”,
data() {
return {
form: {
user: {
name: “Bob”,
email: “Test@test.com
}
},
isTyping: false,
isLoading: false,
}
},
watch: {
form: _.debounce(function() {
this.isTyping = false;
}, 1000),
isTyping: function(value) {
if (!value) {
console.log(“stopped typing”)
}
}
},
methods: {

}
})

HTML

<div id=”app” class=”container-fluid”>
<div class=”row”>
<div class=”col-md-3”>
<label class=”control-label”>Name</label>
<input type=”text” class=”form-control” @input=”isTyping = true” v-model=”form.user.name” placeholder=”Type the keyword”>
<label class=”control-label”>Email</label>
<input type=”text” class=”form-control” @input=”isTyping = true” v-model=”form.user.email” placeholder=”Type the Email”>
</div>
</div>

</div>

Solution :

You need to make the watcher deep

form: {
handler: _.debounce(function() {
this.isTyping = false;
}, 1000),
deep: true
},

Updated fiddle

Vue: How to display unescaped(raw) html

Starting with Vue2, the triple braces were deprecated, you are to use v-html.

1
<div v-html="task.html_content"> </div>

It is unclear from the documentation link as to what we are supposed to place inside v-html, your variables goes inside v-html.

Also, v-html works only with <div> or <span> but not with <template>.

Another example

1
2
<p>Using mustaches: {{ rawHtml }}</p>
<p>Using v-html directive: <span v-html="rawHtml"></span></p>

Dynamically rendering arbitrary HTML on your website can be very dangerous because it can easily lead to XSS vulnerabilities. Only use HTML interpolation on trusted content and never on user-provided content.

Javascript - Regular Expression Tips

Escaping

As we’ve seen, a backslash “\” is used to denote character classes. So it’s a special character.

There are other special characters as well, that have special meaning in a regexp. They are used to do more powerful searches.

Here’s a full list of them: [ \ ^ $ . | ? * + ( ).

se the \ character to escape a character that has special meaning inside a regular expression.

To automate it, you could use this:

1
2
3
function escapeRegExp(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}

RegExp

The RegExp constructor creates a regular expression object for matching text with a pattern.

Syntax

1
2
3
/pattern/flags
new RegExp(pattern[, flags])
RegExp(pattern[, flags])

for the flags

  • g: global match; find all matches rather than stopping after the first match
  • i: ignore case; if u flag is also enabled, use Unicode case folding
  • m: multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string)
  • u: Unicode; treat pattern as a sequence of Unicode code points
  • y: sticky; matches only from the index indicated by the lastIndex property of this regular expression in the target string (and does not attempt to match from any later indexes).